Home > Back-end >  filling column in a list of dataframes with the corresponding column name from each dataframe in R
filling column in a list of dataframes with the corresponding column name from each dataframe in R

Time:09-20

I have a list of dataframes like so:

dflist <- list(df1,df2,..)

[1]
idx_Wafer1  value
1           45.56
2           46.13
3           46.8
4           47.23


[2]
idx_Wafer2  value
1           47.56
2           44.13
3           49.8
4           49.23

I want to add a column named WaferID to each dataframe whose rows contain the valie of the name of the first column id_wafer(n)

Normally I would do:

df1$WaferID <- names(df1[1])
df2$WaferID <- names(df2[1])
etc...

How do I do this on a list of dataframes?

CodePudding user response:

If it is a list, loop over the list with lapply, transform to add a new column with the first column name

dflist <- lapply(dflist, function(dat) transform(dat, WaferID = names(dat)[1]))
  •  Tags:  
  • r
  • Related