Reputation: 589
a <- list()
a[["product_1"]]$sales <- 100
a[["product_1"]]$stock <- 50
a[["product_2"]]$sales <- 200
a[["product_2"]]$stock <- 80
I want to convert to a data frame with columnames = "product" "sales" "stock"
Upvotes: 1
Views: 26
Reputation: 886938
An option is map_dfr
library(purrr)
map_dfr(a, as_tibble, .id = 'product')
Or with bind_rows
library(dplyr)
bind_rows(a, .id = 'product')
# A tibble: 2 x 3
# sales stock product
#* <dbl> <dbl> <chr>
#1 100 50 product_1
#2 200 80 product_2
Or using rbindlist
from data.table
library(data.table)
rbindlist(a, idcol = 'product')
# product sales stock
#1: product_1 100 50
#2: product_2 200 80
Or with base R
do.call(rbind, Map(cbind, lapply(a, as.data.frame), product = names(a)))
Upvotes: 2