R: Multipling df/matrix with 0s and NAs resulting in differiantiated results

I want to multiply a df with a matrix. The df has 0 values and the matrix has NA values (that is important). By multipling a 0 (in df) with a value (in mat) I get 0 and by multiplying a value (in df) with NA (in mat) I get NA, what is true and totally fine for me. However, when I multiply 0 (df) with NA (mat) I get NA, what is probably true. But is there a way to get 0? As I am interested in those 0s. Here some example 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

Answers


I would not directly overwrite the values in mat0 with 0, but rather create a temporary object, or, even easier, use the following line of code

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

The function

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

returns a[b]=c but actually does not change a itself.

Edit: As per request of the OP (see comment below), here some more code.

I assume A[[y]] and x correspond to df0 and mat0, respectively. If so, try

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

One way would be to replace those NA's in mat0 by 0 that are multiplied by 0 in df0. I am not sure how general this solution would be though (i.e. would it work with your actual dataset?):

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

Result:

   a b  c  d e
1 NA 0 NA 20 0

Just as an alternative:

Seems like an ifelse would suffice for this:

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

In which case it deals with the 0 cases.


Need Your Help

subprocess isn't outputting anything

python subprocess pdftotext

I'm trying to use Python to run pdftotext, but for some reason, my code isn't working. If I run the below, I expect that the content variable would contain the contents of the PDF, but the result I...

Devise Authentication for users from Multiple GApps Domains

ruby-on-rails-3 devise omniauth

I have a rails app with Devise 1.4.9. Currently, it allows only users from mydomain.com to use the application. I need to open it up to some contractors that work for me. Their domain is theirdomai...