Reputation: 829
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.
Upvotes: 0
Views: 1755
Reputation: 518
data1<-data.frame(x=1:5,y=2:6)
min<-c(1,2)
s <- sapply(1:length(min),function(x) rep(x,dim(data1)[1]))
data1 <- data1-s
This will create a new matrix s that is made up of columns of the values of your min vector. Subtracting this from data1 will yield your result.
Or use the solution by docendo discimus which is much more elegant:
data1 <- as.data.frame(Map("-", data1, mn))
Upvotes: 1