如何在列的子集中最有效地将0个val设置为NA?

The*_*Cat 0 r

我有一本关于统计的书(使用R),显示以下内容:

> pima$diastolic [pima$diastolic = = 0] <- NA
> pima$glucose [pima$glucose == 0] <- NA
> pima$triceps [pima$triceps == 0] <- NA
> pima$insulin [pima$insulin == 0] <- NA
> pima$bmi [pima$bmi == 0] <- NA
Run Code Online (Sandbox Code Playgroud)

有没有办法在一行或更高效地完成?我看到有一些函数,比如with,apply,subset来做类似的东西,但是无法弄清楚如何将它们组合在一起......

示例数据(如何将其作为数据帧读取(如pythons stringio):

  pregnant glucose diastolic triceps insulin  bmi diabetes age     test
1        6     148        72      35       0 33.6    0.627  50 positive
2        1      85        66      29       0 26.6    0.351  31 negative
3        8     183        64       0       0 23.3    0.672  32 positive
4        1      89        66      23      94 28.1    0.167  21 negative
5        0     137        40      35     168 43.1    2.288  33 positive
6        5     116        74       0       0 25.6    0.201  30 negative
Run Code Online (Sandbox Code Playgroud)

And*_*rie 7

像这样的东西:

  • 使用lapply()使用功能,每列
  • 在函数中,测试列是否为数字.如果是数字,则用NA替换零,否则返回原始列,不变:

试试这个:

pima[] <- lapply(pima, function(x){ if(is.numeric(x)) x[x==0] <- NA else x})
Run Code Online (Sandbox Code Playgroud)

或者对于预定义列

cols = c("diastolic", "glucose", "triceps", "insulin", "bmi")
pima[cols] <- lapply(pima[cols], function(x) {x[x==0] <- NA ; x})
Run Code Online (Sandbox Code Playgroud)

或使用 is.na<-

is.na(pima[cols]) <- pima[cols] == 0
Run Code Online (Sandbox Code Playgroud)