本文介绍了R:取消列出两列数据框(名称,值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从一个命名列表中创建一个两列data.frame(),列表名称出现在第一列中,列表元素出现在第二列中.

From a named list I want to create a two columns data.frame(), with list names appearing in the first column and list elements in the second.

我设法做到了,虽然完成了工作,但还远远不够优雅.

I managed to do this, which get the job done but is far from elegant.

my_list <-
  list("one_digit" = 0:9, "two_digits" = 10:29, "three_digits" = 100:111)

df <-
  data.frame(from = names(unlist(my_list)), to = unlist(my_list), stringsAsFactors = TRUE)

df$from <- gsub("\\d+$","",df$from)

还有其他更优雅的解决方案吗?

Is there any more elegant solution?

推荐答案

将我的评论转换为答案,您可以使用基数R中的stack或"reshape2"中的melt:

Converting my comments to an answer, you can use stack from base R, or melt from "reshape2":

这里是stack:

head(stack(my_list), 15)
##    values        ind
## 1       0  one_digit
## 2       1  one_digit
## 3       2  one_digit
## 4       3  one_digit
## 5       4  one_digit
## 6       5  one_digit
## 7       6  one_digit
## 8       7  one_digit
## 9       8  one_digit
## 10      9  one_digit
## 11     10 two_digits
## 12     11 two_digits
## 13     12 two_digits
## 14     13 two_digits
## 15     14 two_digits

这里是melt:

head(melt(my_list), 15)
##    value         L1
## 1      0  one_digit
## 2      1  one_digit
## 3      2  one_digit
## 4      3  one_digit
## 5      4  one_digit
## 6      5  one_digit
## 7      6  one_digit
## 8      7  one_digit
## 9      8  one_digit
## 10     9  one_digit
## 11    10 two_digits
## 12    11 two_digits
## 13    12 two_digits
## 14    13 two_digits
## 15    14 two_digits

这两种方法之间的区别是,即使列表没有名称,melt也会自动创建"L1"列,并且也可以与嵌套列表一起使用.

One difference between the two approaches is that melt will automatically create the "L1" column even if the list doesn't have names, and will work with nested lists too.

head(melt(unname(my_list)), 15)
##    value L1
## 1      0  1
## 2      1  1
## 3      2  1
## 4      3  1
## 5      4  1
## 6      5  1
## 7      6  1
## 8      7  1
## 9      8  1
## 10     9  1
## 11    10  2
## 12    11  2
## 13    12  2
## 14    13  2
## 15    14  2

这篇关于R:取消列出两列数据框(名称,值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:50