应用函数 jsonlite R
apply function jsonlite R
我有一个简单的data.framedf
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,])
returns:
[{"a":1,"b":10,"c":"A","d":"J"}]
然而,
apply(df[1,], 1, jsonlite::toJSON)
returns:
"[\"1\",\"10\",\"A\",\"J\"]"
我的变量名去哪儿了?我怎样才能让他们回来?
谢谢,
卡洛斯
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"}]
我有一个简单的data.framedf
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,])
returns:
[{"a":1,"b":10,"c":"A","d":"J"}]
然而,
apply(df[1,], 1, jsonlite::toJSON)
returns:
"[\"1\",\"10\",\"A\",\"J\"]"
我的变量名去哪儿了?我怎样才能让他们回来?
谢谢,
卡洛斯
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"}]