简体   繁体   English

R:通过将两个独立的向量相乘来填充缺失值(NA)

[英]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: 我需要用C和r的乘积来填充NA,使其看起来像这样:

      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. 请注意,仅对NA进行乘法运算,而不对已经存在的数字进行乘法运算。 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. 我知道is.na是用来挑选NA的,它可能只是线性代数,但是我的大脑已经is.na一天。 Any help would be great. 任何帮助都会很棒。

Thanks. 谢谢。

If mm is your matrix , you can fill missing values like this: 如果mm是您的矩阵,则可以像这样填充缺失值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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