1

I have iris dataframe. I want to add columns "log_Sepal.Length" and "log_Sepal.Width" which are result of applying log to "Sepal.Length" and "Sepal.Width". I tried:

iris %>% 
  mutate_at(.vars = vars(names(.)[str_detect(names(.), "Sepal")] ), .funs = c("identity", "log"))

but the data frame I Want is :

iris$log_Sepal.Length <- log(iris$Sepal.Length) 
iris$log_Sepal.Width <- log(iris$Sepal.Width)  
iris 

is that possible with mutate_at?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
DD chen
  • 169
  • 11

1 Answers1

4

You can use :

library(dplyr)
iris %>% mutate_at(vars(contains('Sepal')), list(log = ~log(.)))

However, mutate_at has been deprecated, use across from dplyr 1.0.0

iris %>% mutate(across(contains('Sepal'), log, .names = 'log_{col}'))

#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species log_Sepal.Length log_Sepal.Width
#1          5.1         3.5          1.4         0.2  setosa         1.629241        1.252763
#2          4.9         3.0          1.4         0.2  setosa         1.589235        1.098612
#3          4.7         3.2          1.3         0.2  setosa         1.547563        1.163151
#4          4.6         3.1          1.5         0.2  setosa         1.526056        1.131402
#5          5.0         3.6          1.4         0.2  setosa         1.609438        1.280934
#6          5.4         3.9          1.7         0.4  setosa         1.686399        1.360977
#...
#...
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • so It's not possible to also rename new columns at the same time? – DD chen Aug 11 '20 at 10:04
  • You can rename in `across` using `.names` as shown in the answer. What column names do you need? – Ronak Shah Aug 11 '20 at 10:09
  • thanks, but I have no function called "across" , that's because my package "dplyr" is not updated? – DD chen Aug 11 '20 at 13:13
  • Yes, `across` is introduced in `dplyr` 1.0.0. If you have previous version you can use `mutate_at` and then use `rename` to rename the columns according to your choice. – Ronak Shah Aug 11 '20 at 13:15
  • if I use rename, is there a way to add for example "log_" to all columns names start with "Sepal"? – DD chen Aug 11 '20 at 13:33
  • 1
    Perhaps, you can use `iris %>% mutate_at(vars(contains('Sepal')), list(log = ~log(.))) %>% rename_at(vars(ends_with('log')), ~paste0('log_', sub('_log$', '', .)))` – Ronak Shah Aug 11 '20 at 13:43