简体   繁体   中英

Dynamically mutate vector of columns in a list of dataframes

I have a list of dataframes. I want to mutate 2 and 3 column of all the dataframes such that each column= column*3. But I want the names of the column to be same (dynamically created). Here the column names are different in each dataframe. So for example i want 2nd column of all dataframes to get mutiplied by 3 while retaining the same name. simillarly for 3rd column.

so for first dataframe it should be z=z 2, J= j 2 for 2nd dataframe k= k 2,x=x 2 etc.

I want to pass column indices as names might not be fixed.

df_function <- function(n) {
  df <- data.frame(A = sample(n), runif(n), runif(n), rbinom(n, 2, .2))
  names(df)[-1] <- sample(LETTERS[-1], 3)
  return(df)
}

set.seed(123)
df_list1 <- 1:5 %>% map(., ~ df_function(5))


Using data.table (in R 4.1.0 )

library(data.table)
lapply(df_list1, \(x) as.data.table(x)[, (2:3) := .SD * 2, .SDcols = 2:3])

You can use across to specify the columns to multiply by number.

library(dplyr)
library(purrr)

df_list1 <- map(df_list1, ~.x %>% mutate(across(2:3, ~.x * 2)))

Or in base R -

df_list1 <- lapply(df_list1, function(x) {x[2:3] <- x[2:3] * 2;x})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM