Olli J Olli J - 2 months ago 20
R Question

Apply a function to named variables in data.frame

I have a data.frame

a
, and a vector of variables names
alist
:

a <- data.frame(x1=rnorm(20),x2=rnorm(20),x3=rnorm(20),x4=rnorm(20),x5=rnorm(20),x6=rnorm(20),x7=rnorm(20),x8=rnorm(20),x9=rnorm(20),x10=rnorm(20))
alist<-c("x3","x4","x7","x9")


How can I apply a function to
a
so that it affects only variables names in
alist
in a way that doesn't subset
a
? Meaning that the variables from
a
named in
alist
are replaced with the output of the function leaving rest of the variables unaltered.

I can always just run a function, for example
log(a[alist])
and just merge the output with
a
, but there must be a more direct way?

Answer

This generally works :

a[,alist] <- sapply(a[,alist], ...)