Changing specific columns in a data frame list - R

In the list of data frames: ( mylist<-list(iris, mtcars, ToothGrowth)), how can I make changes only to certain columns in the list?

For example, I have a character vector ( test) that gives the column names "Petal.Width"and "drat". How do I match these names with the column names in my list of data frames and apply something like log(x + 1)?

While I can get the necessary columns myself , but I'm not sure how to combine the entire list of data frames and just change the pair of columns. Thanks you

+4
source share
3 answers

First, I define the function you want to apply in your example log(x + 1):

myfun <- function(x) {
  log(x + 1)
}

purrr::map dplyr::mutate_at :

library(tidyverse)
mylist %>% 
  map(~mutate_at(.x, vars(one_of(c("Petal.Width", "drat"))), myfun))

. , . matches(), :

mylist %>% 
  map(~mutate_at(.x, vars(matches("^Petal\\.Width|drat$")), myfun))
+2

test <- c("Petal.Width", "drat")

#Calculate the new value only for those specific columns which we need
value_cols <- lapply(mylist, function(x) log(x[names(x) %in% test]))

value_cols , .

mapply .

mapply(function(x, y) {
  x[names(x) %in% test] <- y
  x }, mylist, value_cols)

value_cols -

value_cols
#[[1]]
#     Petal.Width
#1   -1.60943791
#2   -1.60943791
#3   -1.60943791
#4   -1.60943791
#5   -1.60943791
#...
#...
#[[2]]
#                    drat
#Mazda RX4           1.360977
#Mazda RX4 Wag       1.360977
#Datsun 710          1.348073
#Hornet 4 Drive      1.124930
#Hornet Sportabout   1.147402
#...
#...
#[[3]]
#data frame with 0 columns and 60 rows
+1

Another option is to use intersectwith column names to avoid getting warnings

library(tidyverse)
out <- mylist %>%
           map(~ .x %>%
                  mutate_at(vars(intersect(names(.), test)), myfun))

data

mylist<-list(iris, mtcars, ToothGrowth)
myfun <- function(x) {
 log(x + 1)
}

test <- c("Petal.Width", "drat") 
+1
source

Source: https://habr.com/ru/post/1696082/


All Articles