【发布时间】:2018-02-07 16:19:10
【问题描述】:
考虑数据:
library(data.table)
library(magrittr)
vec1 <- c("Iron", "Copper")
vec2 <- c("Defective", "Passed", "Error")
set.seed(123)
a1 <- sample(x = vec1, size = 20, replace = T)
b1 <- sample(x = vec2, size = 20, replace = T)
set.seed(1234)
a2 <- sample(x = vec1, size = 20, replace = T)
b2 <- sample(x = vec2, size = 20, replace = T)
DT <- data.table(
c(1:20), a1, b1, a2, b2
) %>% .[order(V1)]
names(DT) <- c("id", "prod_name_1", "test_1", "prod_name_2", "test_2")
我需要过滤test_1 OR test_2 的值为"Passed" 的行。因此,如果这些列都没有指定值,则删除该行。对于dplyr,我们可以使用filter_at()动词:
> # dplyr solution...
>
> cols <- grep(x = names(DT), pattern = "test", value = T, ignore.case = T)
>
>
> DT %>%
+ dplyr::filter_at(.vars = grep(x = names(DT), pattern = "test", value = T, ignore.case = T),
+ dplyr::any_vars(. == "Passed")) -> DT.2
>
> DT.2
id prod_name_1 test_1 prod_name_2 test_2
1 3 Iron Passed Copper Defective
2 5 Copper Passed Copper Defective
3 7 Copper Passed Iron Passed
4 8 Copper Passed Iron Error
5 11 Copper Error Copper Passed
6 14 Copper Error Copper Passed
7 16 Copper Passed Copper Error
酷。 data.table有没有类似的方法来执行这个操作?
这是我得到的最接近的:
> lapply(seq_along(cols), function(x){
+
+ setkeyv(DT, cols[[x]])
+
+ DT["Passed"]
+
+ }) %>%
+ do.call(rbind,.) %>%
+ unique -> DT.3
>
> DT.3
id prod_name_1 test_1 prod_name_2 test_2
1: 3 Iron Passed Copper Defective
2: 5 Copper Passed Copper Defective
3: 8 Copper Passed Iron Error
4: 16 Copper Passed Copper Error
5: 7 Copper Passed Iron Passed
6: 11 Copper Error Copper Passed
7: 14 Copper Error Copper Passed
>
> identical(data.table(DT.2)[order(id)], DT.3[order(id)])
[1] TRUE
你们有没有更优雅的解决方案?最好是包含在诸如dplyr::filter_at() 之类的动词中。
【问题讨论】:
-
例如
DT[rowSums(DT[, ..cols] == "Passed") > 0]其中cols包含感兴趣的列 -
您应该在随机化更改所需输出的示例中使用
set.seed(不确定此处是否是这种情况) -
谢谢@Frank。为了重现性的目的,我用
set.seeds 编辑了这个问题。 -
@docendodiscimus 。谢谢,这实际上效果很好,而且速度非常快!
标签: r dplyr data.table