psysky
psysky

Reputation: 3195

print group in R by condition

Say, I have data

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))

by columns x1, x2, x3 we have three groups

q   w   e
w   e   r
r   e   q

I must print only those groups which for act column have only 1 value. In this case, only w e r group has by act column both 0 and 1 value, and another group q w e and r e q has only 1 by act column, so I need to print it.
How to do it?

Expected output

x1  x2  x3
q   w   e
r   e   q

Upvotes: 0

Views: 959

Answers (2)

A. Suliman
A. Suliman

Reputation: 13135

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')

Upvotes: 1

Uwe
Uwe

Reputation: 42592

If I understand correctly, the OP has requested to extract/print only those groups which contain only the value 1 in the act column.

This can be achieved using the all() function.

data.table

library(data.table)
setDT(data)[, which(all(act == 1L)), by = .(x1, x2, x3)][, -"V1"]
   x1 x2 x3
1:  q  w  e
2:  r  e  q

dplyr

library(dplyr)
data %>% 
  group_by(x1, x2, x3) %>% 
  filter(all(act == 1L)) %>% 
  distinct(x1, x2, x3)
# 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

In addition to the dataset data provided by the OP I have tested my answer with a second dataset which contains an additional group and where the rows in the w e r group are ordered differently.

data2 <- data.table::fread(
" x1 x2 x3 var act
  a  b  c  33   0
  a  b  c  33   0
  q  w  e  34   1
  q  w  e  35   1
  w  e  r  34   1
  w  e  r  35   1
  w  e  r  34   0
  w  e  r  35   0
  r  e  q  34   1
  r  e  q  34   1
", data.table = FALSE)

Upvotes: 1

Related Questions