Jackie
Jackie

Reputation: 57

replace NA with data from another column in R

I know how to make the NA's blanks with the following code:

 IMILEFT   IMIRIGHT     IMIAVG
      NA         NA         NA
      NA   71.15127         NA
72.18310   72.86607   72.52458
70.61460   68.00766   69.31113
69.39032   69.91261   69.65146
72.58609   72.75168   72.66888
70.85714         NA         NA
      NA   69.88203         NA
74.47109   73.07963   73.77536
70.44855   71.28647   70.86751
      NA   72.33503         NA
69.82818   70.45144   70.13981
68.66929   69.79866   69.23397
72.46879   71.50685   71.98782
71.11888   71.98336   71.55112
      NA   67.86667         NA

IMILEFT <- ((ASLCOMPTEST$LHML + ASLCOMPTEST$LRML)/(ASLCOMPTEST$LFML +   
             ASLCOMPTEST$LTML)*100)
IMILEFT <- sapply(IMILEFT, as.character)
IMILEFT[is.na(IMILEFT)] <- ""

But when I do that code, it won't allow me to do an average of "IMILEFT" and "IMIRIGHT" or make the "IMIAVG" the same as the other column that has a numerical value.

IMIAVG<-((IMILEFT + IMIRIGHT)/2)

Error in IMILEFT + IMIRIGHT : non-numeric argument to binary operator

It will also be the same error if I make it as.numeric

Upvotes: 0

Views: 175

Answers (1)

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

Try the following. Leave the NAs as they are

rowSums(M, na.rm=TRUE) / 2 - (is.na(L) + is.na(R))

## WHERE
M = cbind(IMILEFT,   IMIRIGHT)
L = IMILEFT   
R = IMIRIGHT

if you have rows were both columns are NA, then have the denominator be

pmin(1, 2 - (is.na(L) + is.na(R)))

Upvotes: 1

Related Questions