[Solved] Transforming numerical variables in a dataframe with a function


You may do:

# data
 head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

the function

foo_divide <- function(x, y){
  foo <- function(x) if(is.numeric(x)) x/1000 else x # function to divide numeric columns by 1000
  if(missing(y)) y <- 1:ncol(x) # set y if missing
  x[, y] <-  lapply(x[, y], foo)
  as.data.frame(x) # return
}

no listofvars

head(foo_divide(iris))
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1       0.0051      0.0035       0.0014       2e-04  setosa
2       0.0049      0.0030       0.0014       2e-04  setosa
3       0.0047      0.0032       0.0013       2e-04  setosa
4       0.0046      0.0031       0.0015       2e-04  setosa
5       0.0050      0.0036       0.0014       2e-04  setosa
6       0.0054      0.0039       0.0017       4e-04  setosa

plus listofvars

 head(foo_divide(iris, c("Petal.Length", "Petal.Width", "Species")))
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5       0.0014       2e-04  setosa
2          4.9         3.0       0.0014       2e-04  setosa
3          4.7         3.2       0.0013       2e-04  setosa
4          4.6         3.1       0.0015       2e-04  setosa
5          5.0         3.6       0.0014       2e-04  setosa
6          5.4         3.9       0.0017       4e-04  setosa

You can also use a numeric vector to specify the columns

foo_divide(iris, 1:3)

solved Transforming numerical variables in a dataframe with a function