x <- data.frame(term = c("A", "B", "C"))
x$points <- list(
data.frame(title=c("Iliad", "Odyssey"), value=c(-1194, -800)),
data.frame(title=c("Iliad", "Odyssey"), value=c(-44, -29)),
data.frame(title=c("Iliad", "Odyssey"), value=c(55, -700))
)
cat(toJSON(x, pretty=TRUE))
title A(value) B(value) C(value)
Iliad -1194 -44 55
Odyssey -800 -29 -700
任何人都可以帮助我获得所需的结果
答案 0 :(得分:3)
library(tidyr)
unnest(x, points) %>%
spread(key = term, value = value)
# title A B C
# 1 Iliad -1194 -44 55
# 2 Odyssey -800 -29 -700
当然,您可以使用"(value)"
将paste
字符串添加到列名称中。我会把它留给你(虽然我认为在列名中包括括号是个坏主意)。
答案 1 :(得分:1)
这样的事情也适用于base R
:
cbind.data.frame(title=x$points[[1]][,1],
do.call(cbind, lapply(1:length(x$term),
function(i) setNames(data.frame(x$points[[i]][,2]), x$term[i]))))
# title A B C
#1 Iliad -1194 -44 55
#2 Odyssey -800 -29 -700
答案 2 :(得分:1)
以下是包含base R
和merge
Reduce
选项
setNames(Reduce(function(...) merge(..., by = 'title'), x$points),
c('title', as.character(x$term)))
# title A B C
#1 Iliad -1194 -44 55
#2 Odyssey -800 -29 -700