1
votes
data1=data.frame("StudentID"=c(1,2,3,4,5),
"Group"=c(A,A,B,B,B),
"cat"=c(2,4,1,3,2),
"fox"=c(3,1,5,1,5),
"score"=c(2,2,2,2,3))




data2=data.frame("StudentID"=c(1,2,3,4,5),
"Group"=c(A,A,B,B,B),
"cat"=c(0.693147181,1.386294361,0,1.098612289,0.693147181),
"fox"=c(1.098612289,0,1.609437912,0,1.609437912),
"score"=c(0.693147181,0.693147181,0.693147181,0.693147181,1.098612289))

I have data1 but wish to achieve data2 where 'cat' and 'fox' and 'score' from data1 are log-transformed to get data2. I am wondering is there a fast efficient solution for this such as data.table? Also I wish to do this by names but also see how it would work with column index numbers!.

1

1 Answers

1
votes

We can apply log on multiple columns

library(data.table)
setDT(data1)[, names(data1)[3:5] := log(.SD), .SDcols = cat:score]
data1
#   StudentID Group       cat      fox     score
#1:         1     A 0.6931472 1.098612 0.6931472
#2:         2     A 1.3862944 0.000000 0.6931472
#3:         3     B 0.0000000 1.609438 0.6931472
#4:         4     B 1.0986123 0.000000 0.6931472
#5:         5     B 0.6931472 1.609438 1.0986123