Вот способ:
L <- list(list(traits = as.list(df[1,])),
list(traits = as.list(df[2,])),
list(traits = as.list(df[3,])))
> toJSON(L, pretty = TRUE, auto_unbox = TRUE)
[
{
"traits": {
"color": "red",
"fruit": "apple",
"animal": "cat"
}
},
{
"traits": {
"color": "blue",
"fruit": "orange",
"animal": "dog"
}
},
{
"traits": {
"color": "green",
"fruit": "grape",
"animal": "chicken"
}
}
]
Чтобы получить этот список L
, вы можете сделать
L <- apply(df, 1, function(x) list(traits = as.list(x)))
Другой способ:
df2 <- purrr::transpose(lapply(df, function(x) as.character(x)))
L <- lapply(df2, function(x) list(traits = x))
или
df <- data.frame(color, fruit, animal, stringsAsFactors = FALSE)
L <- lapply(purrr::transpose(df), function(x) list(traits = x))