您的位置:首页 > 其它

[置顶] 【R语言数据类型】深入了解 向量、矩阵、数据框、列表

2017-05-25 14:54 441 查看
R语言数据类型有向量、矩阵、数据框、列表。下面我们来深入了解下:

vector 的划分

R中的vector分为两类,atomic和list,二者的区别在于,前者元素类型必须相同,后者可以不同。前者的代表是向量和矩阵,后者的代表是list和数据框。

创建向量、矩阵、数据框、列表

# atomic
a <- 1:5
b <- letters[1:5]
c <- 1:10
mat <- matrix(c,nrow=2)

# list
l <- list(a,b,c)
df <-data.frame(a,b)


结果:

> a
[1] 1 2 3 4 5
> b
[1] "a" "b" "c" "d" "e"
> c
[1]  1  2  3  4  5  6  7  8  9 10
>

> mat
[,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10
> l
[[1]]
[1] 1 2 3 4 5

[[2]]
[1] "a" "b" "c" "d" "e"

[[3]]
[1]  1  2  3  4  5  6  7  8  9 10

> df
a b
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
>


is.vector

由于它们都是vector,所以用is.vector检验无法区分向量和列表。当然,也无法用as.vector将列表转换成向量。

is.vector(a) # TRUE

is.vector(l) # TRUE

as.vector(l) # 仍然是list,,没有改变

is.vector(mat) # FALSE

is.vector(df) # FALSE


大家可能注意到了,同样是vector,矩阵和数据框用is.vector检验就返回的是FALSE,这说明is.vector也不是检验vector的,它的真正原理在于,检查是否最多只有一个属性:name。即查看其属性,如果没有属性或者只有一个name属性,才返回TRUE。

attributes(l)  # NULL

attributes(a) # NULL

attributes(df) # 多个属性names row.names class

attributes(mat) #只有一个dim

is.vector的这个功能我现在也不知道有什么用,写在这里只是让大家知道,不要乱用。


要想将list转换成向量,可以用unlist函数

unlist(l)

as.atomic(l) # 报错,没有这个函数

as.list(a) # as.list函数是有的


as.vector的作用也不是把除了names以外的属性全部删掉,它的作用是,当作用对象是atomic时,去除它的所有属性,如果是list则没改变,用is.vector检验也返回FALSE。我们有时用unlist转换后得到的向量是自带名字的,如果不去掉会造成一些麻烦,所以as.vector的一个作用是去除向量的名字属性。

# as.vector作用于list无效
vdf <- as.vector(df)

attributes(vdf) # 属性没有改变

is.vector(vdf) # FALSE

# 转化数据框后向量带有名字
(udf <- unlist(df))

attributes(udf) # 只有一个names属性

vudf <- as.vector(udf)

attributes(vudf) # NULL

# 自己创建带有名字的向量
aaa <- c(1,2,3)

attr(aaa,"names")<-letters[1:3]

aaa

as.vector(aaa)

as.numeric(aaa) # 数值型向量去掉名字还有这种方法

bbb <- c(letters[4:6])

attr(bbb,"names")<- letters[1:3]

bbb

as.vector(bbb)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐