这是关于在R中转换列表。
我的数据如下:
>data = list(list(c('a', 'b'), c('c', 'd')), list(c('a', 'b', 'c'), c('d', 'e', 'f'), c('g', 'h', 'i')))
>data
[[1]]
[[1]][[1]]
[1] "a" "b"
[[1]][[2]]
[1] "c" "d"
[[2]]
[[2]][[1]]
[1] "a" "b" "c"
[[2]][[2]]
[1] "d" "e" "f"
[[2]][[3]]
[1] "g" "h" "i"
我想连接子列表的每个向量,例如paste("a", "b") = "a b")
,以便将整个列表转换为一个数据框,如下所示:
> df <- data.frame(col1 = c("a b", "c d", NA), col2 = c("a b c", "d e f", "g h i"))
> df
col1 col2
1 a b a b c
2 d e d e f
3 <NA> g h i
我现在尝试使用R中的apply-function解决此问题,但这实际上不属于我的领域...提前谢谢您的帮助!
答案 0 :(得分:4)
这是什么。我们使用System.out.println("Hello " + "world");
data.table
和transpose()
中的两个辅助函数。
setDF()
编辑:
无依赖解决方案:
library(data.table)
nrs <- max(lengths(data))
df <- setDF(
lapply(lapply(data, transpose), function(x) do.call(paste, x)[1:nrs])
)
df
# V1 V2
# 1 a b a b c
# 2 c d d e f
# 3 <NA> g h i