将Dataframe转换为LIST

时间:2013-05-14 08:27:32

标签: r list dataframe

我希望将数据帧转换为列表。这是一个示例数据框:

colname   name    age    address
1         John    22     Singapore
2         James   44     India
3         Jessie  21     Australia 

我想将其转换为如下列表:

Name : John Age: 22 Address: Singapore
Name : James Age: 44 Address India
Name : Jessie Age: 21 Address: Australia.

所以基本上我希望在单个R数据类型中获得列名和行的相应值的聚合。

as.list对我不起作用。

1 个答案:

答案 0 :(得分:5)

你可以简单地使用:

 apply(X, 1, function(r) paste(names(X), r, sep=":", collapse=" "))

其中X是您的data.frame

如果您不想要输出中的第一列,请分别添加相应的[, -1][-1]

apply(X[, -1], 1, function(r) paste(names(X)[-1], r, sep=":", collapse=" "))

[1] "name:John age:22 address:Singapore"  
[2] "name:James age:44 address:India"     
[3] "name:Jessie age:21 address:Australia"

但是,如果您的目标是将其转换为JSON,则可以使用rjson包:

library(rjson)
apply(X[,-1], 1, toJSON)

哪个会给你一个适当引用的字符串:

cat( apply(X[,-1], 1, toJSON) )

{"name":"John","age":"22","address":"Singapore"} 
{"name":"James","age":"44","address":"India"}
{"name":"Jessie","age":"21","address":"Australia"}