创建一个数据框,由不同长度的元素列表组成。

huangapple go评论56阅读模式
英文:

Creating a data frame out of a list of element with different length

问题

我有一个具有不同长度数值元素的形式的列表

list1 <- 1:2
list2 <- 1:3
list3 <- c(10, 100)

mylist <- list(a = list1, b = list2, c = list3)

我想将它转换成一个数据框,就像这样

# a 1
# a 2
# b 1
# b 2
# b 3
# c 10
# c 100

有办法可以做到吗?

英文:

I have a with numerical elements of different length of the form

list1 &lt;- 1 : 2
list2 &lt;- 1 : 3
list3 &lt;- c(10, 100)


mylist &lt;- list(a = list1, b = list2, c = list3)

and I would like to transform it into a data frame like this one

# a 1
# a 2
# b 1
# b 2
# b 3
# c 10
# c 100

Is there a way to do it?

答案1

得分: 1

我们可以直接在一个list上应用expand.grid

expand.grid(mylist)

或者使用tidyr中的expand_grid

library(tidyr)
expand_grid(!!!mylist)

对于更新后的数据集:

library(tibble)
enframe(mylist) %>%
  unnest(value)
英文:

We could directly apply expand.grid on a list

expand.grid(mylist)

Or with expand_grid from tidyr

library(tidyr)
expand_grid(!!!mylist)

For the updated dataset

library(tibble)
enframe(mylist) %&gt;% 
  unnest(value)


</details>



# 答案2
**得分**: 0

使用 lapply 替代 expand.grid 的另一种方法:

data.frame(do.call(rbind, lapply(mylist$b, function(x) cbind(x, y = mylist$a))))
   x y
1  1 1
2  1 2
3  1 3
4  1 4
5  1 5
6  2 1
7  2 2
8  2 3
9  2 4
10 2 5
11 3 1
12 3 2
13 3 3
14 3 4
15 3 5
英文:

An alternative to e.g. expand.grid using lapply

data.frame(do.call(rbind, lapply(mylist$b, function(x) cbind(x, y = mylist$a))))
   x y
1  1 1
2  1 2
3  1 3
4  1 4
5  1 5
6  2 1
7  2 2
8  2 3
9  2 4
10 2 5
11 3 1
12 3 2
13 3 3
14 3 4
15 3 5

huangapple
  • 本文由 发表于 2023年2月18日 04:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75489030.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定