将R替换为R

时间:2015-05-14 03:58:45

标签: r math average na sapply

我知道如何使用以下代码制作NA的空白:

 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)] <- ""

但是当我执行该代码时,它不允许我平均执行“IMILEFT”和“IMIRIGHT”或使“IMIAVG”与具有数值的其他列相同。

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

IMILEFT + IMIRIGHT中的错误:二元运算符的非数字参数

如果我将其as.numeric

,也会出现同样的错误

1 个答案:

答案 0 :(得分:1)

尝试以下方法。保留NA原样

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

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

如果你有行,那么两列都是NA,那么分母是

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