1

I am new to R so this is a beginner question.

Currently I have quite a number of data frames from different companies, lets call them a, b, c, d, e, f...

I am trying to:

(1) add one column to each data frame with value equals to the data frame name (I have previously read & named each df from its csv file according to the company)

(2) combine all of them into one big data frame

The result would look similar to:

    col1    col2    new_col
1     1       1       a
2     3       4       a
...
100   1       2       b
101   4       5       b
...
992   3       4       f
993   4       5       f
...

I have tried:

    companies <- list(a, b, c, d, e)
    companies_name <- list("a", "b", "c", "d", "e")
    companies_all <- Map(cbind, companies, company <- companies_name)

but this returned a list of lists. Is there a more elegant way to accomplish this? Please help!

Thank you!


This addressed a somewhat similar question but somehow I could not apply the code. r function/loop to add column and value to multiple dataframes

Community
  • 1
  • 1
AudH
  • 36
  • 6
  • Take a look at the `rbindlist` function from the `data.table` package and its `idcol` argument. – nicola Nov 30 '16 at 09:20

1 Answers1

0
a <- data.frame(col1 = 1:4, col2 = 5:8)
b <- data.frame(col1 = 11:14, col2 = 15:18)

ldfs <- list(a = a, b = b)
for (df_name in names(ldfs))
  ldfs[[df_name]][["new_col"]] <- df_name
df <- do.call(rbind, ldfs)
rownames(df) <- NULL

output:

> df
  col1 col2 new_col
1    1    5       a
2    2    6       a
3    3    7       a
4    4    8       a
5   11   15       b
6   12   16       b
7   13   17       b
8   14   18       b
John Smith
  • 1,077
  • 6
  • 21