R中unlist函数的使用

蹲街弑〆低调 提交于 2020-04-03 09:06:51

买的书里面实例讲的不清不楚,所以看帮助文档了

用法:unlist(x, recursive = TRUE, use.names = TRUE)

帮助文档讲x可以是向量或者列表,如果是向量,则原样返回,尝试下,确实如此,向量并不是典型的用法。

> x<-c(1,2,3)
> unlist(x)
[1] 1 2 3
> names(x)<-c("first","second","third")
> x
first second third
1 2 3
> unlist(x)
first second third
1 2 3
> unlist(x,use.names=F)
first second third
1 2 3
> unlist(x,recursive=FALSE)
first second third
1 2 3
如果使用列表,一般情况下,如果recursive = FALSE,则unlist只会作用于列表的第一层,向量(矩阵看成有维度的向量,应该相同处理)元素会取出向量的单个值作为unlist后的项,列表元素(数据框作为特殊列表?)则取出列表元素的组成作为项。use.names = FALSE,则是否使用元素名称,命名方法为元素名称(.下一层元素名称)+1,2,3组成,从列到行读取数据,无名称则对应向量名称为空。数字会适应统一类型可能转变为字符。

如果元素是因子,则返回的值为因子对应的1,2,3,4水平。names, formulas and calls这些列表元素返回的很可能还是列表,另论。

> y<-list(name=c("peter","john","mike"),ages=c(24,35,68),c(88,99),am=list(try=c(1,2),uk=matrix(1:6,2,3))
+ )
> y
$name
[1] "peter" "john" "mike"

$ages
[1] 24 35 68

[[3]]
[1] 88 99

$am
$am$try
[1] 1 2

$am$uk
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6


> unlist(y)
name1 name2 name3 ages1 ages2 ages3 am.try1 am.try2 am.uk1 am.uk2 am.uk3 am.uk4 am.uk5 am.uk6
"peter" "john" "mike" "24" "35" "68" "88" "99" "1" "2" "1" "2" "3" "4" "5" "6"
> unlist(y,use.names=FALSE)
[1] "peter" "john" "mike" "24" "35" "68" "88" "99" "1" "2" "1" "2" "3" "4" "5" "6"
> unlist(y,recursive=FALSE)
$name1
[1] "peter"

$name2
[1] "john"

$name3
[1] "mike"

$ages1
[1] 24

$ages2
[1] 35

$ages3
[1] 68

[[7]]
[1] 88

[[8]]
[1] 99

$am.try
[1] 1 2

$am.uk
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6

> unlist(y,recursive=FALSE,use.names=FALSE)
[[1]]
[1] "peter"

[[2]]
[1] "john"

[[3]]
[1] "mike"

[[4]]
[1] 24

[[5]]
[1] 35

[[6]]
[1] 68

[[7]]
[1] 88

[[8]]
[1] 99

[[9]]
[1] 1 2

[[10]]
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6

> y$fc<-factor(c("a","b","a","c","b"))
> y$fc2<-factor(c("jj","kk","jj"))
> y
$name
[1] "peter" "john" "mike"

$ages
[1] 24 35 68

[[3]]
[1] 88 99

$am
$am$try
[1] 1 2

$am$uk
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6


$fc
[1] a b a c b
Levels: a b c

$fc2
[1] jj kk jj
Levels: jj kk

> unlist(y)
name1 name2 name3 ages1 ages2 ages3 am.try1 am.try2 am.uk1 am.uk2 am.uk3 am.uk4 am.uk5 am.uk6 fc1
"peter" "john" "mike" "24" "35" "68" "88" "99" "1" "2" "1" "2" "3" "4" "5" "6" "1"
fc2 fc3 fc4 fc5 fc21 fc22 fc23
"2" "1" "3" "2" "1" "2" "1"

> z<-list(add=factor(c("a","d","a")),add1=factor(c("a","b","c","d","a")),FB=list(bd=c("33","66"),c(8,9)))
> unlist(z)
add1 add2 add3 add11 add12 add13 add14 add15 FB.bd1 FB.bd2 FB3 FB4
"1" "2" "1" "1" "2" "3" "4" "1" "33" "66" "8" "9"

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!