Reputation: 6713
suppose I have
# test case
a<-matrix(rep(c(1,2,3,4,5,6),3),ncol=3)
b<-t(matrix(c(1,3,4)))
a
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 2 2 2
[3,] 3 3 3
[4,] 4 4 4
[5,] 5 5 5
[6,] 6 6 6
b
[,1] [,2] [,3]
[1,] 1 3 4
Each element of b
"corresponds" to a column of a
and needed in a function as follows:
I have a function myFun
myfun<-function(x,n) {
x[1:n]<-NA
x
}
and I want to use it to return
t<-cbind(myfun(a[,1],b[1]), myfun(a[,2],b[2]), myfun(a[,3],b[3]))
t
[,1] [,2] [,3]
[1,] NA NA NA
[2,] 2 NA NA
[3,] 3 NA NA
[4,] 4 4 NA
[5,] 5 5 5
[6,] 6 6 6
How can I achieve the above using apply
/ lapply
/ sapply
without using a for
loop?
For instance, I try apply(a,2,FUN=myfun,b)
, then the whole b
is passed to myfun
instead of b[1]
or b[2]
etc.
How can I rewrite apply(a,2,FUN=myfun,b)
such that myfun
will only pick up that element of b
corresponding to the respective column of a
?
Upvotes: 1
Views: 176
Reputation: 66834
You can just use vector subsetting for this task:
(NAcells <- unlist(sapply(seq_along(b), function(i) seq(b[i])+(i-1)*nrow(a))))
[1] 1 7 8 9 13 14 15 16
a[NAcells] <- NA
a
[,1] [,2] [,3]
[1,] NA NA NA
[2,] 2 NA NA
[3,] 3 NA NA
[4,] 4 4 NA
[5,] 5 5 5
[6,] 6 6 6
Upvotes: 1