Why does this not work ?
data1<-data.frame(x=1:5,y=2:6) onevector<-c(1,2) lapply(1:length(onevector),function(i) {data1[,i]<-data1[,i]-onevector[i]}) data1 remains unchanged...
I try to substract one element to each column of my dataset data1, I want to do :
data1[,1]<- data1[,1] -1 (which is working out of the lapply) data1[,2]<- data1[,2] -2 My question is more about understanding the difference between lapply and for than about an alternative way to implement this, so please elaborate your answer if you want to answer.
data1:data1[] <- lapply(1:length(min),function(i) {data1[,i]<-data1[,i]-min[i]})lapply. Btw, you could do this usingdata1[] <- Map("-", data1, min)lapplyis conceptionally different from aforloop. You are trying to use it like aforloop, which can't work.lapplyis much more in line with functional programming, e.g., it applys a function on each element of its first parameter and changes to local objects in a function have no effect on global objects.