简体   繁体   中英

R: Filling Missing Values (NA) by Multiplying Two Separate Vectors

I'm having a brain-freeze.

This is what I have:

C <- c(C1, C2, C3)  # A constant for every row in the data frame
r <- c(r1, r2, r3, r4)   # A ratio for every column in the data frame

My data frame looks like this:

     1    2    3   4
a   0.7  0.4   NA  NA
b    NA   NA  0.3  NA
c    NA  0.6   NA 0.4

I need to fill in the NA's with a multiplication of C and r so that it looks like this:

      1      2     3        4
a    0.7    0.4   C1*r3   C1*r4
b   C2*r1  C2*r2   0.3    C2*r4
c   C3*r1   0.6   C3*r3    0.4

Notice that the multiplication is only done for the NA's and not for numbers that already exist. I know is.na is used to pick out the NA's, and it's probably just linear algebra, but my brain has quit for the day. Any help would be great.

Thanks.

If mm is your matrix , you can fill missing values like this:

mm[is.na(mm)] <- outer(C,r)[is.na(mm)]

example with data :

mm <- read.table(text='   1    2    3   4
a   0.7  0.4   NA  NA
b    NA   NA  0.3  NA
c    NA  0.6   NA 0.4')

C <- c(1, 1, 1)  # A constant for every row in the data frame
r <- c(2, 2, 2, 2) 

mm[is.na(mm)] <- outer(C,r)[is.na(mm)]

#    X1  X2  X3  X4
# a 0.7 0.4 2.0 2.0
# b 2.0 2.0 0.3 2.0
# c 2.0 0.6 2.0 0.4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM