我的数据框如下:
structure(list(intype = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L,
3L, 3L), .Label = c("A30", "A31", "E45"), class = "factor"),
inerror = c(0.54, 0.14, 0.94, 0, 2.11, 0, 1.42, 3.19, 0),
inmethod = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L
), .Label = c("A", "B", "C"), class = "factor")), row.names = c(NA,
-9L), class = "data.frame")
+--------+---------+----------+
| intype | inerror | inmethod |
+--------+---------+----------+
| A30 | 0.54 | A |
| A30 | 0.14 | B |
| A30 | 0.94 | C |
| A31 | 9.20 | A |
| A31 | 2.11 | B |
| A31 | -1.55 | C |
| E45 | 1.42 | A |
| E45 | 3.19 | B |
| E45 | 0.00 | C |
+--------+---------+----------+
Intype
是一个因素。
如果inerror<=0
,我想从一个因素中删除所有行。
因此,结果数据帧将是:
+--------+---------+----------+
| intype | inerror | inmethod |
+--------+---------+----------+
| A30 | 0.54 | A |
| A30 | 0.14 | B |
| A30 | 0.94 | C |
+--------+---------+----------+
答案 0 :(得分:2)
多种方法
library(dplyr)
df %>%
group_by(intype) %>%
filter(all(inerror > 0))
# intype inerror inmethod
# <fct> <dbl> <fct>
#1 A30 0.54 A
#2 A30 0.14 B
#3 A30 0.94 C
或者它是反向版本
df %>%
group_by(intype) %>%
filter(!any(inerror <= 0))
以基数R ave
subset(df, ave(inerror > 0, intype, FUN = all))
#and
subset(df, !ave(inerror <= 0, intype, FUN = any))
答案 1 :(得分:2)
这也可以。
with(dat, dat[- which(intype %in% intype[inerror <= 0]), ])
或更短(thx @Ronak Shah )
with(dat, dat[!intype %in% intype[inerror <= 0], ])
# intype inerror inmethod
# 1 A30 0.54 A
# 2 A30 0.14 B
# 3 A30 0.94 C
要摆脱过时的因素,请在新数据框上使用droplevels
。
dat$intype <- droplevels(dat$intype)