简体   繁体   English

将向量列表列表转换为 R 中的数据帧

[英]Transform List of List of Vectors into Dataframe in R

This is about transforming lists in R.这是关于在 R 中转换列表。

My data looks as follows:我的数据如下所示:

>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"

I would like to concatenate every vector of the sublists, eg paste("a", "b") = "ab") , so that the whole list can be transformed into a dataframe, that looks as follows:我想连接子列表的每个向量,例如paste("a", "b") = "ab") ,以便整个列表可以转换为数据框,如下所示:

> 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

I tried to solve this problem now with the apply-functions in R, but this is really not my territory... Thx in advance for your help!我现在试图用 R 中的应用函数来解决这个问题,但这真的不是我的领域......提前感谢您的帮助!

Here is something.这里有一些东西。 We use two helper functions from data.table transpose() and setDF() .我们使用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

EDIT:编辑:

Dependency-free solution:无依赖解决方案:

as.data.frame(sapply(data, function(x) sapply(x, paste, collapse = " ")[1:nrs]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM