我有一个可变长度的列表。每个嵌套列表的第一个值是键,列表中的其余值将是数组条目。看起来是这样的:
[[1]]
[1] "Bob"      "Apple"
[[2]]
[1] "Cindy"    "Apple"     "Banana"      "Orange"   "Pear"   "Raspberry"         
[[3]]
[1] "Mary"     "Orange"    "Strawberry"
[[4]]
[1] "George"   "Banana"我提取的密钥和条目如下:
keys <- lapply(x, '[', 1)
entries <- lapply(x, '[', -1)但是现在我有了这些,我不知道如何关联一个键:R中的值对,而不首先创建一个矩阵,但这是愚蠢的,因为我的数据无论如何都不适合于矩形(我看到的每个例子都使用来自矩阵的列名作为键值)。
这是我使用矩阵、分配行名、然后使用jsonLite导出到JSON的糟糕方法。
#Create a matrix from entries, without recycling
#I found this function on StackOverflow which seems to work...
cbind.fill <- function(...){
  nm <- list(...) 
  nm <- lapply(nm, as.matrix)
  n <- max(sapply(nm, nrow)) 
  do.call(cbind, lapply(nm, function (x) 
    rbind(x, matrix(, n-nrow(x), ncol(x))))) 
}
#Call said function
matrix <- cbind.fill(entries)
#Transpose the thing
matrix <- t(matrix)
#Set column names
colnames(matrix) <- keys
#Export to json
json<-toJSON(matrix)结果是好的,但是实现很糟糕。结果:
[{"Bob":["Apple"],"Cindy":["Apple","Banana","Orange","Pear","Raspberry"],"Mary":["Orange","Strawberry"],"George":["Banana"]}]请让我知道可能有更好的方法来实现这一点。
发布于 2016-03-30 20:18:56
我认为这个问题已经得到了充分的回答,但是这里有一个使用purrr和jsonlite的方法。
library(purrr)
library(jsonlite)
sample_data <- list(
  list("Bob","Apple"),
  list("Cindy","Apple","Banana","Orange","Pear","Raspberry"),
  list("Mary","Orange","Strawberry"),
  list("George","Banana")
)
sample_data %>%
  map(~set_names(list(.x[-1]),.x[1])) %>%
  toJSON(auto_unbox=TRUE, pretty=TRUE)https://stackoverflow.com/questions/36227993
复制相似问题