I am trying to figure out how to perform the same calculation in a dataframe for multiple dataframes at the same time. I am working with 56 different dataframes with all the same column names, deriving from multiple data sources.
I want to do a very simple column calculation, like this one underneath.
df1 <- data.frame( EF = c(1, 3, 5, 2, 5), FF = c(0.5, 0.7, 0.4, 1, 0.8))
df2 <- data.frame( EF = c(1, 1, 5, 7, 6), FF = c(0.4, 0.2, 0.1, 0.9, 0.2))
df1$CF <- df1$EF * df1$FF
df2$CF <- df2$EF * df2$FF
Now, I have to do this for df1 to df56, just this simple multiplication of these two columns. To do this manually, it takes a lot of time and I am quite sure to be able to do this for multiple dataframes at the same time with a for loop or a function command, but I cannot manage to find a clear instruction. Hopefully one of you can help me out!
CodePudding user response:
IF there are multiple datasets, place them in a list
and then do the calculation in the list
by looping over the list
lst1 <- lapply(list(df1, df2), transform, CF = EF * FF)
Placing them in the list
can be easy if the object names created have a pattern i.e. df1, df2, ...df56 with mget
and paste
or with mget
and ls(pattern = '^df\\d $')
lst1 <- lapply(mget(paste0('df', 1:56)), transform, CF = EF * FF)