您正在寻找的实际上是lapply
一些应用程序rbind
或相关的组合。
我会稍微扩展你的数据,只是为了有两个以上的元素。
eg <- c("{\"3x\": 20, \"6y\": 23}",
"{\"3x\": 60, \"6y\": 50}",
"{\"3x\": 99, \"6y\": 72}")
library(jsonlite)
使用base R,我们可以做
do.call(rbind.data.frame, lapply(eg, fromJSON))
# X3x X6y
# 1 20 23
# 2 60 50
# 3 99 72
你可能想做类似的事情Reduce(rbind, lapply(eg, fromJSON))
,但显着的区别是在Reduce
模型中,rbind
被称为“N-1”次,其中“N”是 ; 中的元素数eg
。这会导致大量的数据复制,虽然它可能适用于小的“N”,但它的扩展性非常糟糕。使用该do.call
选项,rbind
仅调用一次。
请注意,列标签已被 R 化,因为data.frame
列名不应以数字开头。(这是可能的,但通常不鼓励。)
如果您确信所有子字符串都将具有完全相同的元素,那么您在这里可能会很好。如果有机会在某个时候会有所不同,也许
eg <- c(eg, "{\"3x\": 99}")
然后您会注意到基本 R 解决方案在默认情况下不再有效。
do.call(rbind.data.frame, lapply(eg, fromJSON))
# Error in (function (..., deparse.level = 1, make.row.names = TRUE, stringsAsFactors = default.stringsAsFactors()) :
# numbers of columns of arguments do not match
可能有一些技术可以尝试规范化元素,以便您可以确保匹配。但是,如果您不反对一个tidyverse
包:
library(dplyr)
eg2 <- bind_rows(lapply(eg, fromJSON))
eg2
# # A tibble: 4 × 2
# `3x` `6y`
# <int> <int>
# 1 20 23
# 2 60 50
# 3 99 72
# 4 99 NA
尽管您不能直接使用美元方法调用它,但您仍然可以使用[[
或反引号。
eg2$3x
# Error: unexpected numeric constant in "eg2$3"
eg2[["3x"]]
# [1] 20 60 99 99
eg2$`3x`
# [1] 20 60 99 99