按条件在R中打印组

时间:2018-08-03 11:19:47

标签: r dataframe dplyr data.table

说,我有数据

data=structure(list(x1 = structure(c(1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L), .Label = c("q", 
"r", "w"), class = "factor"), x2 = structure(c(2L, 2L, 2L, 2L, 
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), .Label = c("e", "w"), class = "factor"), x3 = structure(c(1L, 
1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 
2L, 2L, 2L), .Label = c("e", "q", "r"), class = "factor"), var = c(34L, 
35L, 34L, 34L, 34L, 34L, 35L, 34L, 34L, 34L, 34L, 35L, 34L, 34L, 
34L, 34L, 34L, 34L, 34L, 34L), act = c(1L, 1L, 1L, 1L, 1L, 0L, 
0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("x1", 
"x2", "x3", "var", "act"), class = "data.frame", row.names = c(NA, 
-20L))

通过x1x2x3列,我们分为三组

q   w   e
w   e   r
r   e   q

我必须仅打印act列中只有1个值的那些组。 在这种情况下,只有w e r组的act列具有0和1值,并且 另一组q w er e q的{​​by {1}}列中只有1个,因此我需要打印它。
怎么做?

预期产量

act

2 个答案:

答案 0 :(得分:1)

library(dplyr)
data %>% distinct(x1,x2,x3, .keep_all = TRUE) %>% 
         filter(act==1) %>% select(-var,-act)

  x1 x2 x3
1  q  w  e
2  r  e  q

data %>% distinct(x1,x2,x3, .keep_all = TRUE) %>% 
         filter(act==1) %>% select(-var,-act) %>%
         filter(x1=='r',x2=='e',x3=='q')

  x1 x2 x3
1  r  e  q


#OR 
data %>% filter(x1=='r',x2=='e',x3=='q')

答案 1 :(得分:1)

如果我理解正确,则OP要求仅提取/打印.s1 { top: 60px; position: absolute; will-change: transform; margin-left: 20px; transform: translate3d(20px,0,0); transition: transform 0.8s ease; } 列中仅包含值1的那些组。

这可以使用act函数来实现。

data.table

all()
library(data.table)
setDT(data)[, which(all(act == 1L)), by = .(x1, x2, x3)][, -"V1"]

dplyr

   x1 x2 x3
1:  q  w  e
2:  r  e  q
library(dplyr)
data %>% 
  group_by(x1, x2, x3) %>% 
  filter(all(act == 1L)) %>% 
  distinct(x1, x2, x3)

数据

除了OP提供的数据集# A tibble: 2 x 3 # Groups: x1, x2, x3 [2] x1 x2 x3 <fct> <fct> <fct> 1 q w e 2 r e q 之外,我还用另一个数据集测试了我的答案,该数据集包含一个附加组,并且data组中的行以不同的顺序排列。

w e r