R: multiplication of the df / matrix with 0s and NA, leading to differentiated results

I want to multiply df by matrix. Df has 0 values, and the matrix has NA values ​​(which is important). By multiplying 0 (in df) with the value (in mat), I get 0 and multiplying the value (in df) by NA (in mat), I get NA, which is true and perfectly normal for me. However, when I multiply 0 (df) with NA (mat), I get NA, which is probably true. But is there a way to get 0? Since I'm interested in these 0. Here are some sample data:

df0 <- data.frame(a=1, b=0, c=2, d=5, e=0)
mat0 <- matrix(c(NA,2,NA,4,NA),nrow=1, ncol=5)
df_mat0 <- df0 * mat0

My expected result (0 in e):

   a b  c  d  e
1 NA 0 NA 20  0

Ideas? Thanks

+4
source share
3 answers

mat0 0, , ,

df0*`[<-`(mat0,df0==0,0)
#   a b  c  d e
#1 NA 0 NA 20 0

`[<-`(a,b,c)

a[b]=c, a.

: OP (. ), .

, A[[y]] x df0 mat0, . ,

Map(function(x,y) A[[y]]*`[<-`(x,A[[y]]==0,0),B,sub('\\..*','',names(B)))
+1

NA mat0 0, 0 df0. , (.. ?):

mat0[df0 == 0][is.na(mat0[df0 == 0])] <- 0
df0 * mat0

:

   a b  c  d e
1 NA 0 NA 20 0
+1

:

, ifelse:

unlist(ifelse(df0 == 0L, 0, mat0 * df0))
[1] NA  0 NA 20  0

0.

+1
source

Source: https://habr.com/ru/post/1618571/


All Articles