[英]Splitting List into dataframe 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
你可以试试:
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
您可以使用基本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)
)
或在stack()
的帮助下对tidyr::separate()
的简单调用。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.