R语言 将列表对象转换为具有两列的嵌套框架

nzkunb0c  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(106)

我有一个列表对象“list”,它包含多个列表,结构如下。列表中的所有对象都有这样的两个字母:

[[1]]
[1] "A" "C"

[[2]]
[1] "A" "D"

[[3]]
[1] "C" "D"

我想转换它,这样我就得到了一个像这样的两列的嵌套框架:
| 源|目标|
| --|--|
| 一|C|
| 一|D|
| C| D|
有没有办法做到这一点?
我可以在网上找到的所有例子都是每个对象中有一个观察的列表,除了这个在每个列表元素中有标签的例子:
Converting a list of lists to a dataframe in R: The Tidyverse-way

gwo2fgha

gwo2fgha1#

你想把列表元素绑定在一起吗?rbind()

# mock up data:
obj <- list(list("a","b"), list("a", "d"), list("c","d"))

# binding:
df <- do.call(rbind, obj)
df

> df
     [,1] [,2]
[1,] "a"  "b" 
[2,] "a"  "d" 
[3,] "c"  "d"

然后你只需要按照通常的方式对列名等进行排序。

vhipe2zx

vhipe2zx2#

你有几种可能性,让我们首先使用基R,然后也使用Tidyverse-way

# Option 1: Base R---------------------
# Don't use function names as identifiers, so I really recommend that "list"
# is renamed to sth like "multiple.lst" or sth. else. But will leave it for OP purposes.
list<- list(
  c("A", "C"),
  c("A", "D"),
  c("C", "D")
)

df <-
  do.call(rbind, lapply(list, function(x)
    data.frame(Source = x[1], Target = x[2])))

And the otuput:

  Source Target
1      A      C
2      A      D
3      C      D

#2 Tidyverse way------------------------
library(tidyverse)

df <- list %>% 
#  map_df: to iterate over each element of the list
  map_df(~data.frame(Source = .[1], Target = .[2]))

输出与选项1相同。

相关问题