[R] apply for each value

Sarah Goslee sarah.goslee at gmail.com
Tue Oct 11 18:12:50 CEST 2011


Hi,

On Tue, Oct 11, 2011 at 12:08 PM, Ben qant <ccquant at gmail.com> wrote:
> Hello,
>
> There has to be a more R'ish way to do this. I have two matrices, one has
> the values I want, but I want to NA some of them. The other matrix has
> binary values that tell me if I want to NA the values in the other matrix. I
> produce a third matrix based on this. I've also tried apply() passing in
> c(1,2) for rows and columns with no success yet.
>
> Example (this works, but I'm looking for a better/faster solution):
>
> a = matrix(1:6,2,3)
> colnames(a) = c('a','b','c')
> b = matrix(c(1,0,1,0,0,1),2,3)
> colnames(b) = colnames(a)
> c = matrix(0,nrow(a),ncol(a))
> for(cl in 1:ncol(a)){
>  for(rw in 1:nrow(a)){
>    c[rw,cl] = ifelse(b[rw,cl]==1,a[rw,cl],NA)
>  }
>
> }

You're making it far too complicated. No need for loops or apply() or
anything like that.

> c <- a
> c[b == 0] <- NA
> c
      a  b  c
[1,]  1  3 NA
[2,] NA NA  6

And thanks for the reproducible small example.

Sarah

>> a
>     a b c
> [1,] 1 3 5
> [2,] 2 4 6
>> b
>     a b c
> [1,] 1 1 0
> [2,] 0 0 1
>> c
>     [,1] [,2] [,3]
> [1,]    1    3   NA
> [2,]   NA   NA    6
>
>
> Thanks!
>
> Ben
>



-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list