Home > front end >  how to refer specific column of an entire list of dataframes in R function?
how to refer specific column of an entire list of dataframes in R function?

Time:08-20

I have a multitude of dataframes in R that are like this & I know how to modify an entire column.

id    fire  earth   water 
1     5       7       9
2     23      34      54
3      1      2        3


df$fire <- (df$fire-5.5)/4.5

Im having a hard time finding the specific syntax to refer to this specific column but of every df (lets say fire)

df.list <- list(df1,df2,df3)

fire_function <- function(){(.$fire-5.5)/4.5}

lapply(df.list, fire_function)

Sorry if this question was already asked, i searched and couldn't find how to refer a specific column of all dataframes. Maybe my apply function is not appropriate either.

thank you

CodePudding user response:

We can use transform

df.list <- list(df1 = df1, df2 = df2, df3 = df3)
df.list <- lapply(df.list, transform, fire = (fire  - 5.5)/4.5)

If we need to update the original datasets, use list2env

list2env(df.list, .GlobalEnv)

Or we may need to assign and then return the data

df.list <- lapply(df.list, function(x) {
                x$fire <- (x$fire - 5.5)/4.5
                x})

Or create the fire_function as

fire_function <- function(x) {
                  x$fire <- (x$fire - 5.5)/4.5
                  x
     }
df.list <- lapply(df.list, fire_function)
  •  Tags:  
  • r
  • Related