R语言 list类型数据转换

时间:2022-01-14 21:13:24

例如:

> a=list(c('232','34'),c('good','bad'),c(1,5))
> a
[[1]]
[1] "232" "34"

[[2]]
[1] "good" "bad"

[[3]]
[1] 1 5
> names(a)=c('d','w','j')
> a
$d
[1] "232" "34"

$w
[1] "good" "bad"

$j
[1] 1 5

>

list数据类型取值用[[ ]],如:

> a[[1]]
[1] "232" "34"
> a[1]
$d
[1] "232" "34"

>

现将list类型转换成常用的数据类型:
1、unlist

> unlist(a)
d1 d2 w1 w2 j1 j2
"232" "34" "good" "bad" "1" "5"
>

可通过列名取值。

2、do.call
可使用do.call(rbind,x)和do.call(cbind,x)函数转换成矩阵:

> do.call(rbind,a)
[,1] [,2]
d "232" "34"
w "good" "bad"
j "1" "5"
> do.call(cbind,a)
d w j
[1,] "232" "good" "1"
[2,] "34" "bad" "5"