将列表拆分为数据框R

时间:2019-02-14 02:57:28

标签: r

我正在尝试将此列表拆分为长格式的数据框

list_a <- list(`Blue Banana` = 8.7, `Green Strawberry` = 2.3, 
               `Blue Squash` = 3.5, `Orange Cherry` = 4.5)

,以便第一列在列表中所有项目的名称(橙色,蓝色,绿色)中包含第一个单词,第二列在名称(香蕉,樱桃,草莓,南瓜)中包含第二个单词。然后,第3列将具有匹配的值。具有这些列名称的数据框应该看起来像这样

Color  Fruit      value
Blue   Banana       8.7
Green  Strawberry   2.3
Blue   Squash       3.5
Orange Cherry       4.5

2 个答案:

答案 0 :(得分:4)

您可以尝试:

library(tidyverse)

list_a %>% 
  bind_rows %>%
  gather %>%
  separate(col = key, sep = " ", c("Color", "Fruit"))

# A tibble: 4 x 3
  Color  Fruit      value
  <chr>  <chr>      <dbl>
1 Blue   Banana       8.7
2 Green  Strawberry   2.3
3 Blue   Squash       3.5
4 Orange Cherry       4.5

答案 1 :(得分:3)

您可以使用基数R中的read.table()执行此操作。

cbind(
    read.table(text=names(list_a), col.names=c("Color", "Fruit")), 
    value=unlist(list_a, use.names=FALSE)
)
#    Color      Fruit value
# 1   Blue     Banana   8.7
# 2  Green Strawberry   2.3
# 3   Blue     Squash   3.5
# 4 Orange     Cherry   4.5

或使用strcapture()

cbind(
    strcapture("(.+) (.+)", names(list_a), data.frame(Color="", Fruit="")), 
    value=unlist(list_a, use.names=FALSE)
)

或者在tidyr::separate()的帮助下,对stack()的简单调用。

tidyr::separate(stack(list_a), ind, c("Color", "Fruit"))
#   values  Color      Fruit
# 1    8.7   Blue     Banana
# 2    2.3  Green Strawberry
# 3    3.5   Blue     Squash
# 4    4.5 Orange     Cherry
相关问题