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

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

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

问题

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

  1. list1 <- 1:2
  2. list2 <- 1:3
  3. list3 <- c(10, 100)
  4. mylist <- list(a = list1, b = list2, c = list3)

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

  1. # a 1
  2. # a 2
  3. # b 1
  4. # b 2
  5. # b 3
  6. # c 10
  7. # c 100

有办法可以做到吗?

英文:

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

  1. list1 &lt;- 1 : 2
  2. list2 &lt;- 1 : 3
  3. list3 &lt;- c(10, 100)
  4. mylist &lt;- list(a = list1, b = list2, c = list3)

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

  1. # a 1
  2. # a 2
  3. # b 1
  4. # b 2
  5. # b 3
  6. # c 10
  7. # c 100

Is there a way to do it?

答案1

得分: 1

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

  1. expand.grid(mylist)

或者使用tidyr中的expand_grid

  1. library(tidyr)
  2. expand_grid(!!!mylist)

对于更新后的数据集:

  1. library(tibble)
  2. enframe(mylist) %>%
  3. unnest(value)
英文:

We could directly apply expand.grid on a list

  1. expand.grid(mylist)

Or with expand_grid from tidyr

  1. library(tidyr)
  2. expand_grid(!!!mylist)

For the updated dataset

  1. library(tibble)
  2. enframe(mylist) %&gt;%
  3. unnest(value)
  4. </details>
  5. # 答案2
  6. **得分**: 0

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

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

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

  1. data.frame(do.call(rbind, lapply(mylist$b, function(x) cbind(x, y = mylist$a))))
  2. x y
  3. 1 1 1
  4. 2 1 2
  5. 3 1 3
  6. 4 1 4
  7. 5 1 5
  8. 6 2 1
  9. 7 2 2
  10. 8 2 3
  11. 9 2 4
  12. 10 2 5
  13. 11 3 1
  14. 12 3 2
  15. 13 3 3
  16. 14 3 4
  17. 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:

确定