对象(R语言是面向对象的解释型语言)
1、查看一个对象的模式:mode()
2、所有对象都有的特征是长度(length):length()
3、其实一个对象还有其它更多的属性,而模式与长度只是众多属性中的两个很特别的属性,称为内在属性
想查看对象其他的属性,可以使用:attributes(),见下例(特别注意属性的引用 $)
> x
[1] 1 1 1 1 1
> length(x)
[1] 5
> mode(x)
[1] "numeric"
> attributes(x)
NULL
> x <- c(89, 99)
> names(x) <- c("math", "english")
> x
math english
89 99
> attributes(x)
$names
[1] "math" "english"
4、模式转换:as.character() as.numeric() as.logical() as.integer() as.complex() 见下例
> x <- c(1, 3, 4, 6, 7)
> y = as.character(x)
> y = as.numeric(y)
> x <- c(1, 3, 4, 6, 7)
> y <- as.character(x)
> y
[1] "1" "3" "4" "6" "7"
> mode(y)
[1] "character"
> print(y, quote=FALSE)
[1] 1 3 4 6 7
> y <- as.numeric(y)
> y
[1] 1 3 4 6 7
> mode(y)
[1] "numeric"
> y <- as.integer(y)
> y
[1] 1 3 4 6 7
> mode(y)
[1] "numeric"
> y
[1] TRUE TRUE TRUE TRUE TRUE
> y <- as.integer(y)
> y
[1] 1 1 1 1 1
> y <- as.complex(y)
> y
[1] 1+0i 1+0i 1+0i 1+0i 1+0i
> e <- numeric()
> e
numeric(0)
> mode(e)
[1] "numeric"
> e[3] <- "3"
> e
[1] NA NA "3"
> e <- as.integer(e)
> e
[1] NA NA 3
> e <- 1:10
> e
[1] 1 2 3 4 5 6 7 8 9 10
> e <- e[2*1:5]
> e
[1] 2 4 6 8 10
> length(e) < 3
[1] FALSE
> length(e) <- 3
> e
[1] 2 4 6
注意:函数attr(object, name) 可以用来选择特定的属性。这些函数很少用到 6 ,只是在一些非常特殊的情况下,如为特定目的设计一些新属性时才使用。6、如何了解对象?你知道你面对的对象是什么吗?可以看下面几个例子:
> z
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
>
> class(z)
[1] "matrix"
> x
[1] 1 3 4 6 7
> class(x)
[1] "numeric"
> str(x)
num [1:5] 1 3 4 6 7
> str(z)
int [1:10, 1:10] 1 2 3 4 5 6 7 8 9 10 ...
> attributes(z)
$dim
[1] 10 10