统计分析与R软件-chapter2-3

2.3 对象和它的模式与属性

R是一种基于对象的语言,R的对象包含了若干个元素作为其数据,另外还可以有一些特殊数据称为属性,并规定了一些特定操作(如打印、绘图)。比如,一个向量是一个对象,一个图形也是一个对象。R对象分为单纯对象和复合对象两种,单纯对象的所有元素都是同一种基本类型(如数值、字符串),元素不再是对象;复合对象的元素可以是不同类型的对象,每个元素是一个对象。

2.3.1 固有属性:mode 和length

> mode(c(1,3,5)>5)
[1] "logical"
> z<-0:9
> is.numeric(z)
[1] TRUE
> is.character(z)
[1] FALSE
> length(2:4)
[1] 3
> length(z)
[1] 10

强制类型转换

> digits<-as.character(z);digits
 [1] "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"
> d<-as.numeric(digits);d
 [1] 0 1 2 3 4 5 6 7 8 9

2.3.2 修改对象的长度

> x<-numeric();x
numeric(0)
> x[3]<-17;x
[1] NA NA 17
> x<-1:3
> x<-4:9
> x<-x[1:2];x
[1] 4 5
> alpha <- 1:10
> alpha <- alpha[2*1:5];alpha
[1]  2  4  6  8 10
> length(alpha)<- 3;alpha
[1] 2 4 6

2.3.3 attributes() 和 attr()函数

attributes(object)返回对象object的各特殊属性组成的列表,不包括固有属性mode和length

> x<- c(apple=2.5,orange=2.1);x
 apple orange 
   2.5    2.1 
> attributes(x)
$names
[1] "apple"  "orange"

用attr(object,name)的形式存取对象object的名为name的属性

> attr(x,"names")
[1] "apple"  "orange"
> attr(x,"names")<- c("apple","grapes");x
 apple grapes 
   2.5    2.1 
> attr(x,"type");attr(x,"type")<-"fruit";x
NULL
 apple grapes 
   2.5    2.1 
attr(,"type")
[1] "fruit"
> attributes(x)
$names
[1] "apple"  "grapes"

$type
[1] "fruit"

2.3.4 对象的class属性

在R中可以用特殊的class属性来支持面向对象的编程风格,对象的class属性用来区分对象的类,可以写出通用函数根据对象类的不同进行不同的操作,比如,print()函数对于向量和矩阵的显示方法就不同,plot()函数对不同类的自变量做不同的图形

为了暂时去掉一个有类的对象的class属性,可以用unclass(object)

原文地址:https://www.cnblogs.com/SweetZxl/p/chapter23.html