2

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


0

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.