Jin
Jin

Reputation: 555

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

Upvotes: 1

Views: 2240

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

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

Upvotes: 3

lroha
lroha

Reputation: 34441

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

Upvotes: 4

Related Questions