1

I have a list like this:

require(tidyverse)
months <- c("january", "february", "march", "october", "december") 
weekdays <- c("Sunday", "Monday", "Tuesday")
seasons <- c("Summer", "Winter", "Fall", "autumn")
timeWords_list <- tibble::lst(months,  weekdays, seasons)

I want to convert this list into a two columns-data.frame: I need all the values of the list to be in the first column And the tags to be the values of the second column

The result should be like this:

df <- data.frame(first_column  = c("january", "february", "march", "october", "december", "Sunday", "Monday", "Tuesday", "Summer", "Winter", "Fall", "autumn"), 
                 second_column = c("months", "months", "months", "months", "months", "weekdays", "weekdays" ,"weekdays", "seasons", "seasons", "seasons", "seasons"))

The second column could be a string or a factor, but should correspond to tags of the list. Note that the list could be of different sizes and its elements could have different lengths.

3 Answers3

2

An easy option is stack from base R

df1 <- stack(timeWords_list)
names(df1) <- c("first_column", "second_column")
akrun
  • 674,427
  • 24
  • 381
  • 486
1

I think the stack approach by @akrun is the most efficient one so far. Here is another base R option using unlist + rep

data.frame(
  first_col = unlist(timeWords_list, use.names = FALSE),
  second_col = rep(names(timeWords_list), lengths(timeWords_list))
)

which gives

   first_col second_col
1    january     months
2   february     months
3      march     months
4    october     months
5   december     months
6     Sunday   weekdays
7     Monday   weekdays
8    Tuesday   weekdays
9     Summer    seasons
10    Winter    seasons
11      Fall    seasons
12    autumn    seasons
ThomasIsCoding
  • 53,240
  • 4
  • 13
  • 45
0

Using tibble::enframe and tidyr::unnest

tibble::enframe(timeWords_list,name = 'first_column',value = 'second_column') %>%
  tidyr::unnest(second_column)

# first_column second_column
#   <chr>        <chr>        
# 1 months       january      
# 2 months       february     
# 3 months       march        
# 4 months       october      
# 5 months       december     
# 6 weekdays     Sunday       
# 7 weekdays     Monday       
# 8 weekdays     Tuesday      
# 9 seasons      Summer       
#10 seasons      Winter       
#11 seasons      Fall         
#12 seasons      autumn       
Ronak Shah
  • 286,338
  • 16
  • 97
  • 143