suppose I want to log transform columns in a data frame, say iris
data and create new ones with the suffix _log
dynamically for each desired column.
What I am trying to achieve is:
df$Sepal.Length_log <- log (df$Sepal.Length)
df$Sepal.Width_log <- log (df$Sepal.Width)
df$Petal.Length_log <- log (df$Petal.Length)
df$Sepal.Width_log <- log (df$Sepal.Width)
but this would be a tedious task when your data have many columns to transform, so I want to achieve this dynamically using a loop and mutate
function of the dplyr
package, my unsuccessful naive trial was:
library (dplyr)
data(iris)
varLabel <- c('Sepal.Length','Sepal.Width','Petal.Length','Petal.Width')
for (i in 1:length (varLabel)) {
varNew <- paste (varLabel[i],'log',sep='_')
iris <- dplyr::mutate (iris,varNew=log (varLabel[i])) # problem arises here
}
I get this error: Error: non-numeric argument to mathematical function
I searched for a solution and the most relevant one seems to be this tutorial on standard and non-standard evaluation, this post and that one also, but I couldn't figure out how to borrow a solution from there. Any help would be much appreciated.
Note:
I want to have both old and new columns in the data set.