Nithin .M
Nithin .M

Reputation: 85

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=z2, J= j2 for 2nd dataframe k= k2,x=x2 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))


Upvotes: 2

Views: 313

Answers (2)

akrun
akrun

Reputation: 887851

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])

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389235

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})

Upvotes: 0

Related Questions