Reputation: 119
I have a list that's called my_list and looks like this:
$love
playing working sleeping
0.43 0.56 0.88
$will
otherwise rework rule
0.87 0.23 0.11
$new
car shirt
0.23 0.12
I want to convert it to the following dataframe, with the output looking like this:
Column 1 Column 2 Column 3
love playing 0.43
love working 0.56
love sleeping 0.88
will otherwise 0.87
will rework 0.23
will rule 0.11
new car 0.23
new shirt 0.12
I have tried this
df <- do.call(rbind,lapply(cor1,as.data.frame))
but then the columns become the default columns of the dataframe:
love.playing 0.43
love.working .56
and so on (basically i have only one column with the numbers). Any help will be much appreciated.
Upvotes: 1
Views: 56
Reputation: 39858
One tibble
and purrr
option could be:
map_df(my_list, ~ enframe(., name = "Column2", value = "Column3"), .id = "Column1")
Column1 Column2 Column3
<chr> <chr> <dbl>
1 love playing 0.43
2 love working 0.56
3 love sleeping 0.88
4 will otherwise 0.87
5 will rework 0.23
6 will rule 0.11
7 new car 0.23
8 new shirt 0.12
Upvotes: 2
Reputation: 173793
You can do this:
df <- as.data.frame(do.call(rbind, strsplit(names(unlist(my_list)), "[.]")))
df$Column3 <- unlist(my_list)
names(df)[1:2] <- c("Column1", "Column2")
df
#> Column1 Column2 Column3
#> 1 love playing 0.43
#> 2 love working 0.56
#> 3 love sleeping 0.88
#> 4 will otherwise 0.87
#> 5 will rework 0.23
#> 6 will rule 0.11
#> 7 new car 0.23
#> 8 new shirt 0.12
Upvotes: 1
Reputation: 33488
out <- stack(my_list)
out$col2 <- row.names(out)
row.names(out) <- NULL
out
# values ind col2
# 1 0.43 love playing
# 2 0.56 love working
# 3 0.88 love sleeping
# 4 0.87 will otherwise
# 5 0.23 will rework
# 6 0.11 will rule
# 7 0.23 new car
# 8 0.12 new shirt
Reproducible data (please share next time):
my_list <- list(
love = c(playing = 0.43, working = 0.56, sleeping = 0.88),
will = c(otherwise = 0.87, rework = 0.23, rule = 0.11),
new = c(car = 0.23, shirt = 0.12)
)
Upvotes: 4