0

我有一个简单的 data.frame df

a    b    c     d
1    5    A     E
2    4    B     F
3    3    C     G
4    2    D     H
5    1    E     J

假设我想以 JSON 格式编写它:

jsonlite::toJSON(df[1,])

返回:

[{"a":1,"b":10,"c":"A","d":"J"}]

然而,

apply(df[1,], 1, jsonlite::toJSON)

返回:

"[\"1\",\"10\",\"A\",\"J\"]"

我的变量名去哪儿了?我怎样才能让他们回来?

谢谢,

卡洛斯

4

1 回答 1

0

help(apply)告诉你:

 If ‘X’ is not an array but an object of a class with a non-null
 ‘dim’ value (such as a data frame), ‘apply’ attempts to coerce it
 to an array via ‘as.matrix’ if it is two-dimensional (e.g., a data
 frame) or via ‘as.array’.

所以toJSON看到了一个数据帧的每一行的字符向量。

解决方案是拆分数据框并使用lapply

> lapply(split(df, 1:nrow(df)), jsonlite::toJSON)
$`1`
[{"a":1,"b":5,"c":"A","d":"E"}] 
$`2`
[{"a":2,"b":4,"c":"B","d":"F"}] 
$`3`
[{"a":3,"b":3,"c":"C","d":"G"}] 
$`4`
[{"a":4,"b":2,"c":"D","d":"H"}] 
$`5`
[{"a":5,"b":1,"c":"E","d":"I"}] 
于 2015-02-26T16:07:20.630 回答