4

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

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对我不起作用。

4

1 回答 1

6

你可以简单地使用:

 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"}
于 2013-05-14T08:35:06.583 回答