0

我在这里看到了类似的问题,但我找不到任何帮助。

我有一个这样的df:

df <- data.frame(CSF1=c(-9,-9,-9,-9), CSF2=c(-9,-1,-9,-9), 
               D13S1=c(-9,-9,11,11), D13S2=c(-9,-9,11,12))

         CSF1 CSF2 D13S1 D13S2 
10398     -9   -9   -9    -9                   
10398     -9   -1   -9    -9                             
20177     -9   -9   11    11                  
20361     -9   -9   11    12           

我想删除所有列的值为 -9 或 -1 的所有行,例如前 2 行。

谢谢!

4

2 回答 2

3

All I will add is that the which function doesn't appear to be necessary. Removing it yields the same result.

There is a secondary problem that you would have in situations with missing data. If, you add an NA to the 3rd row (try it with df[3,4] <- NA), then the output of the above solution will omit the 3rd row as well regardless of the other entries' values. I won't suggest alternatives as this may not be a problem for your data set.

于 2013-05-02T06:46:57.690 回答
2

试试这个(由 Arun 编辑以说明 Dov 的帖子):

df[rowSums(df == -1 | df == -9, na.rm = TRUE) != ncol(df), ]
##   CSF1 CSF2 D13S1 D13S2
## 3   -9   -9    11    11
## 4   -9   -9    11    12

(df == -1 | df == -9)会给你逻辑矩阵。rowSumsTRUE在每一行中为您提供计数,因为TRUE被评估为1. 这na.rm=TRUE是为了确保NA不会省略带有的行(请参阅 Dov 的帖子)。使用结果行号来设置子集df

于 2013-05-02T05:08:21.560 回答