0

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.

17
  • what are you trying to achieve, what is your expected output? Commented Feb 25, 2016 at 10:22
  • 1
    You have to assignt the result back to data1: data1[] <- lapply(1:length(min),function(i) {data1[,i]<-data1[,i]-min[i]}) Commented Feb 25, 2016 at 10:24
  • the affectation should already do that, no ??? Commented Feb 25, 2016 at 10:26
  • 2
    No, the object in the global environment is not changed by the lapply. Btw, you could do this using data1[] <- Map("-", data1, min) Commented Feb 25, 2016 at 10:27
  • 3
    lapply is conceptionally different from a for loop. You are trying to use it like a for loop, which can't work. lapply is 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. Commented Feb 25, 2016 at 10:33

1 Answer 1

1
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)) 
Sign up to request clarification or add additional context in comments.

4 Comments

You can avoid the as.data.frame call by using data1[] <- Map("-", data1, min). The empty brackets [] will keep the structure of data1 (i.e. a data.frame)
Very elegant solution indeed.
Yes I do prefer the solution of @docendodiscimus, or I can do a loop, but my question was more about understanding than implementing.
My guess would be that the function inside lapply modifies a "new" data1 in local scope and does not touch the previously exsisting data1 in local scope. This question seems to be related: stackoverflow.com/questions/13640157/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.