Greg Rov Greg Rov - 2 months ago 6
R Question

how to perform log10 transform on specific columns by a condition in R

May dataset is like this:

d <- read.table('age.txt', header = F,sep=' ')

V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 101 12 3.531704 16.0 40.8 1.449648 1.080353 20.85738 74.53056 0
2 102 15 -9.000000 24.0 36.4 -9.000000 -9.000000 -9.00000 -9.00000 0
3 103 13 3.306023 26.2 48.4 2.178820 1.349228 22.51904 72.82571 2.3
4 104 12 2.715226 18.2 42.6 2.343138 1.414314 23.13632 72.73414 4.5


and I need to perform log10 transform on column 6:10, but only for the values that are not equal to 0 or -9. Well, I tried this:

if(d[,6:10]!=-9 || 0){d[,6:10]=log10(d[,6:10])}


but it did not work. If anyone can help thanks.

Answer

One option would be to loop through the columns 6:10, get the index of elements that are not 0 or -9, apply the log10 on those and return the vector.

d[6:10] <-  lapply(d[6:10], function(x)  {
                 i1 <- !x %in% c(0, -9)
                 x[i1] <- log10(x[i1])
                 x} ) 

Or another option would be to create a logical matrix ('i1') subset the elements from the columns and update with the log10

i1 <- d[6:10]!=0 & d[6:10] != -9
d[6:10][i1] <- log10(d[6:10][i1])
Comments