I would like to combine multiple dataframes but before that I'd like to add the name of the dataframe as character string in each entry of a new column. I'm almost there but don't see the problem. Code:
df1 <- data.frame("X1"=c(1,1),"X2"=c(1,1))
df2 <- data.frame("X1"=c(2,2),"X2"=c(2,2))
df3 <- data.frame("X1"=c(3,3),"X2"=c(3,3))
addCol <- function(df){df$newCol <- deparse(substitute(df)); df}
# Extracts name of dataframe and writes it into entries of newCol
alldfsList <- lapply(list(df1,df2,df3), function(df) x <- addCol(df))
# Should apply addCol function to all dataframes, generates a list of lists
alldfs <- do.call(rbind, alldfsList) # Converts list of lists into dataframe
The problem is that the second command doesn't write the name of the dataframe into the column entries, but the placeholder, "df". But when I apply the addCol function manually to a single dataframe, it works. Can you help? Thanks!
Output:
> alldfs
X1 X2 newCol
1 1 1 df
2 1 1 df
3 2 2 df
4 2 2 df
5 3 3 df
6 3 3 df
>
Function applied to a single df works:
> addCol(df1)
X1 X2 newCol
1 1 1 df1
2 1 1 df1
>