AudH AudH - 5 days ago 5
R Question

In R, add NEW column to MULTIPLE df using df names

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

Answer
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
Comments