56.ADR之R中数据结构之Vecctors
自此帖开始的一段帖子基本上都会是摘自Advanced R的内容,比较适合进阶的R user,本来想重新开个帖子来记录的,想想还是从一而忠吧[s:11],更喜欢看原书的可以点这里
首先R有基本的5种数据结构:
atomic vector,list,matrix,data frame,array
最基本的数据结构是Vectors这个大类,其中分为atomic vector和list两个小类,主要区别就是其中的数据类型是不是一致,共同点就是都有3个主要的性质typeof(),length(),attributes(),我们平常用的最多的c() (combine的意思) 就是指atomic vector,list嘛大家就比较熟悉了,所以判断一个东西是不是vector,可以is.atomic(x)||is.list(x),有人问为什么不is.vector(x),这里涉及到比较深的原因,反正有些东西就是不知道会出错啊!
下面来仔细讲atomic vectors:
这个结构又有4种基本类型,logical,integer,double,character以及大家暂时不必理会的2种类型complex,raw
dbl_var <- c(1, 2.5, 4.5)<br />
# With the L suffix, you get an integer rather than a double<br />
int_var <- c(1L, 6L, 10L)<br />
# Use TRUE and FALSE (or T and F) to create logical vectors<br />
log_var <- c(TRUE, FALSE, T, F)<br />
chr_var <- c("these are", "some strings")
我们平常说的numericl类型,其实是说integer或double
具体看类型就是前面说的typeof()以及is.integer(),is.atomic(),is.numeric()的is.系列
int_var <- c(1L, 6L, 10L)<br />
typeof(int_var)<br />
#> [1] "integer"
所以到这里,相信很多人会明白到底什么是typeof()什么是class()(这个class是后面要说的attributes中的一种),我以前就是混,觉得type和class是一个意思吧,当然mode()又是什么(等以后弄清楚吧,这里提一下)?
对于length()没什么好说的,唯一注意的是
a=1<br />
length(a)<br />
[1] 1
也就是说这是一个长度为1的integer 类型的atomic vector,更需要提到的是NA,是长度为1的logical类型的atomic vector,与此同时还有NA_real_ (a double vector), NA_integer_ and NA_character_这些类型!!!
R>length(NA)<br />
[1] 1<br />
R>is.logical(NA)<br />
[1] TRUE<br />
R>is.atomic(NA)<br />
[1] TRUE<br />
R>is.character(NA_character_)<br />
[1] TRUE<br />
R>is.character(NA)<br />
[1] FALSE
对于atomic vector,也就是通常的c(),还有要注意的是强制转换的顺序: logical, integer, double and character,也就是说你的c()里的东西本来应该是同一类型的,结果你弄了不同类型,那就按上面的顺序转
R>c(1,TRUE,2.5,'a')<br />
[1] "1" "TRUE" "2.5" "a"
这就都变character了
还有个attributes先讲lists:
lists由于可以放任一类型,所以其实就没什么好说的了,要注意的是
c(list(1,2),c(3,4))<br />
list(list(1,2),c(3,4))
结果是不一样的,前者的c()会把c()中的东西变成list再和list合并起来,具体大家试验下
对于lists,typeof()的结果还是list,也有个把list变成atomic vector的方法就是unlist(),如果list本身放的
东西类型不同,那么变成c()的结果和前面介绍的c()中强制转换结果一样
lists被用来构造很多R中的复杂的数据结构,例如lm(),data.frames
mod <- lm(mpg ~ wt, data = mtcars)<br />
is.list(mod)<br />
#> [1] TRUE
list的length()也就没什么好说的了
好,下面来介绍attributes():
这是个复杂的概念,不适合新手读,所有的对象都可以有额外的属性,我们可以这样设置
y <- 1:10<br />
attr(y, "my_attribute") <- "This is a vector"<br />
attr(y, "my_attribute")<br />
#> [1] "This is a vector"<br />
str(attributes(y))
原话是: Attributes can be accessed individually with attr() or all at once (as a list) with attributes().
或者
structure(1:10, my_attribute = "This is a vector")
当我们改动一个vector的时候,这个属性就会丢失比如上面设置了y的属性,我们
attributes(y[1])<br />
#> NULL<br />
attributes(sum(y))<br />
#> NULL
这就引出了,3个不会丢失的attributes:
names,dimensions,class(s3) s3,s4是什么大家暂时不必关心,我也不懂。。。
引用方式是: names(x), class(x) and dim(x), 而不是 attr(x, "names"), attr(x, "class"), and attr(x, "dim").这三个东西也是会陆续的出现在下面要介绍的数据结构中。
PS:介绍比较复杂的东西,自己也觉得写的比较乱。。。大家就这样看吧[s:11]
</p>