R-Code Related question,

There is 2 column in the data frame categorical variable:

ID Var1
1 A1
1 A2
1 A3
2 A1
2 A2
3 A1
3 A2
3 A3
3 A2

I would like to code if ID contained all A1+A2+A3 then code into one A unit, that means according to the table above ID (1) & (3) contain A but ID (2) does not have A. I would like to make a new table with results.

One option is to use tidyr::pivot_wider to reshape your table so you can apply a dplyr::filter.

For example,

library(dplyr)
library(tidyr)
df <- tibble(
  ID = c(1,1,1,2,2,2),
  Var1 = c("A1", "A2", "A3", "A1","A2","A4")
) %>% 
  mutate(value = TRUE)
df %>% pivot_wider(names_from = Var1, values_from = value) %>% 
  filter(A1, A2, A3) %>% 
  select(ID)
#> # A tibble: 1 x 1
#>      ID
#>   <dbl>
#> 1     1

Created on 2020-05-19 by the reprex package (v0.3.0)

Thank you very much Curtis. I really appreciate it. work well for me.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.