Home > Software design >  Subtracting list elements from another list in R
Subtracting list elements from another list in R

Time:06-13

I have two lists and I want to subtract one list element wise with the other, in order to replicate a Matlab function bsxfun(@minus, lt, lt2). The two lists look something like the below (edit: now works without pracma package):

# Code 

# First list
lt = c(list())

# I use these lines to pre-dim the list...
lt[[1]] = c(rep(list(1)))
lt[[2]] = c(rep(list(1)))

# ... such that I can add matrices it this way:
lt[[1]][[1]] = matrix(c(3),nrow=1, ncol=1,byrow=TRUE)
lt[[2]][[1]] = matrix(c(1),nrow=1, ncol=1, byrow=TRUE)

# Same with the second list:
lt2 = c(list())
lt2[[1]] = c(rep(list(1)))
lt2[[2]] = c(rep(list(1)))

lt2[[1]][[1]] = matrix(c(2,2,2),nrow=3, ncol=1,byrow=TRUE)
lt2[[2]][[1]] = matrix(c(1,1,1),nrow=3, ncol=1,byrow=TRUE)

Element wise subtraction would mean that that each row of an element of lt2 would be subtracted by the respective element of the object lt, i.e., lt2[[1]][[1]] each row by 3, resulting in t(c(-1 -1 -1)).... and lt2[[2]][[1]] = t(c(0,0,0)) by 1 ... It is important to me that the list structure is maintained in the results.

Now I tried using lapply(lt2,"-",lt) but it does not work. Any suggestions?

CodePudding user response:

I suspect you are looking for something like this skeleton code which subtracts 2 lists element-wise...

x <- list(1,2,3)
y <- list(4,5,6)
mapply('-', y, x, SIMPLIFY = FALSE)

but as noted, you need 2 identical lists (or at least R's recycling algorithms must make sense) as for example...

z <- list(4,5,6,7,8,9)
mapply('-',z,x,SIMPLIFY = FALSE)

You might be looking for something like this where you subtract a constant from each member of the list...

mapply('-',y,2, SIMPLIFY= FALSE)

CodePudding user response:

I figured it out - I had another mistake in the question :/

Changing the second class as.numeric worked

lt3 = lapply(lt2[[1]],"-",as.numeric(lt[[1]]))

  • Related