Home > OS >  Use purrr on a list to mutate on different cols
Use purrr on a list to mutate on different cols

Time:11-27

I have a list of dataframes

alist=list(mtcars=mtcars,iris=iris)

I want to log transform a different col in each:

cols=c( "hp", "Sepal.Width")

How could I do this with lmap or a similar purrr fun? Many thanks!

CodePudding user response:

You could do this via purrr::map2 like so:

library(dplyr)
library(purrr)

alist=list(mtcars=mtcars,iris=iris)
cols=c( "hp", "Sepal.Width")

blist <- map2(alist, cols, ~ mutate(.x, !!sym(.y) := log(.data[[.y]])))

map(blist, head)
#> $mtcars
#>                    mpg cyl disp       hp drat    wt  qsec vs am gear carb
#> Mazda RX4         21.0   6  160 4.700480 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag     21.0   6  160 4.700480 3.90 2.875 17.02  0  1    4    4
#> Datsun 710        22.8   4  108 4.532599 3.85 2.320 18.61  1  1    4    1
#> Hornet 4 Drive    21.4   6  258 4.700480 3.08 3.215 19.44  1  0    3    1
#> Hornet Sportabout 18.7   8  360 5.164786 3.15 3.440 17.02  0  0    3    2
#> Valiant           18.1   6  225 4.653960 2.76 3.460 20.22  1  0    3    1
#> 
#> $iris
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1    1.252763          1.4         0.2  setosa
#> 2          4.9    1.098612          1.4         0.2  setosa
#> 3          4.7    1.163151          1.3         0.2  setosa
#> 4          4.6    1.131402          1.5         0.2  setosa
#> 5          5.0    1.280934          1.4         0.2  setosa
#> 6          5.4    1.360977          1.7         0.4  setosa

EDIT In case of multiple cols you could do:

cols=list(mtcars=c("hp","disp"),iris=c( "Sepal.Length" ,"Sepal.Width")) 

blist <- map2(alist, cols, ~ mutate(.x, across(all_of(.y), ~ log(.x))))

map(blist, head)
#> $mtcars
#>                    mpg cyl     disp       hp drat    wt  qsec vs am gear carb
#> Mazda RX4         21.0   6 5.075174 4.700480 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag     21.0   6 5.075174 4.700480 3.90 2.875 17.02  0  1    4    4
#> Datsun 710        22.8   4 4.682131 4.532599 3.85 2.320 18.61  1  1    4    1
#> Hornet 4 Drive    21.4   6 5.552960 4.700480 3.08 3.215 19.44  1  0    3    1
#> Hornet Sportabout 18.7   8 5.886104 5.164786 3.15 3.440 17.02  0  0    3    2
#> Valiant           18.1   6 5.416100 4.653960 2.76 3.460 20.22  1  0    3    1
#> 
#> $iris
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1     1.629241    1.252763          1.4         0.2  setosa
#> 2     1.589235    1.098612          1.4         0.2  setosa
#> 3     1.547563    1.163151          1.3         0.2  setosa
#> 4     1.526056    1.131402          1.5         0.2  setosa
#> 5     1.609438    1.280934          1.4         0.2  setosa
#> 6     1.686399    1.360977          1.7         0.4  setosa
  • Related