2

I have a list like below.

p1

$ColA
     Var1 Freq
1   asgfg  2.1
2     dds  2.1
3     dfg  4.3
4     dfh  2.1

$ColB
  Var1 Freq
1    A 44.7
2    B 55.3

What I need looks like below. Basically, I want to combine them into a single dataframe.

df

Col      Var1   Freq
ColA     asgfg  2.1
ColA     dds    2.1
ColA     dfg    4.3
ColA     dfh    2.1
ColB      A     44.7
ColC      B     55.3
M--
  • 25,431
  • 8
  • 61
  • 93
Dev P
  • 449
  • 3
  • 12

2 Answers2

5

One option is bind_rows

library(dplyr)
bind_rows(p1, .id = 'Col')
#   Col  Var1 Freq
#1 ColA asgfg  2.1
#2 ColA   dds  2.1
#3 ColA   dfg  4.3
#4 ColA   dfh  2.1
#5 ColB     A 44.7
#6 ColB     B 55.3

Or with base R

out <- do.call(rbind, Map(cbind, Col = names(p1), p1))
row.names(out) <- NULL

data

p1 <- list(ColA = structure(list(Var1 = c("asgfg", "dds", "dfg", "dfh"
), Freq = c(2.1, 2.1, 4.3, 2.1)), class = "data.frame", row.names = c("1", 
"2", "3", "4")), ColB = structure(list(Var1 = c("A", "B"), Freq = c(44.7, 
55.3)), class = "data.frame", row.names = c("1", "2")))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Perfect. But I get error message ````Warning messages: 1: In bind_rows_(x, .id) : Unequal factor levels: coercing to character 2: In bind_rows_(x, .id) : binding character and factor vector, coercing into character vector 3: In bind_rows_(x, .id) : binding character and factor vector, coercing into character vector```` – Dev P Oct 01 '19 at 17:54
  • @DevP It is a warning message. Nothing to worry about it. Occurs when you have `factor` columns. If it is a `character` columns, there is no issue with unequal factors. Please check the `data` in my post – akrun Oct 01 '19 at 17:55
  • 1
    @DevP It is not an error message. Error will not give an output – akrun Oct 01 '19 at 18:01
  • is there a way to get the `col` column using `plyr::rbind.fill(p1)`? – M-- Oct 01 '19 at 18:41
0

We can use data.table package:

data.table::rbindlist(p1, idcol = "col")

or using purrr:

purrr::map_df(p1, I, .id = "col")

Getting:

#     col  Var1 Freq
# 1: ColA asgfg  2.1
# 2: ColA   dds  2.1
# 3: ColA   dfg  4.3
# 4: ColA   dfh  2.1
# 5: ColB     A 44.7
# 6: ColB     B 55.3

Using the data provided in akrun's answer

M--
  • 25,431
  • 8
  • 61
  • 93