简体   繁体   中英

Splitting List into dataframe R

I'm trying to split this list into a long form dataframe

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

such that the first column includes the first word in the name of all items in the list (Orange, Blue, Green) and the second column has the second word in the name (Banana, Cherry, Strawberry, Squash). Then the 3rd column will have the values matched. The dataframe should look like this with these column names

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

You can try:

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

You can do this with read.table() in base R.

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

Or with strcapture() .

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

Or a simple call to tidyr::separate() with the help of 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM