Skip to content

Instantly share code, notes, and snippets.

@trinker
Created September 9, 2019 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trinker/45acf350373ac8e4588e8311b0043436 to your computer and use it in GitHub Desktop.
Save trinker/45acf350373ac8e4588e8311b0043436 to your computer and use it in GitHub Desktop.
Rowwise subsets in dplyr
library(dplyr)
dat <- tibble(
x1=c(1,0,0,NA,0,1,1,NA,0,1),
x2=c(1,1,NA,1,1,0,NA,NA,0,1),
x3=c(0,1,0,1,1,0,NA,NA,0,1),
y4=c(1,0,NA,1,0,0,NA,0,0,1),
y5=c(1,1,NA,1,1,1,NA,1,0,1),
z = LETTERS[1:10]
)
dat %>%
mutate(
x = select(., matches('^x')) %>% apply(1, sum, na.rm=TRUE),
y = select(., matches('^y')) %>% {as.integer(apply(., 1, sum, na.rm=TRUE) > 0)}
)
## x1 x2 x3 y4 y5 z x y
## 1 1 1 0 1 1 A 2 1
## 2 0 1 1 0 1 B 2 1
## 3 0 NA 0 NA NA C 0 0
## 4 NA 1 1 1 1 D 2 1
## 5 0 1 1 0 1 E 2 1
## 6 1 0 0 0 1 F 1 1
## 7 1 NA NA NA NA G 1 0
## 8 NA NA NA 0 1 H 0 1
## 9 0 0 0 0 0 I 0 0
## 10 1 1 1 1 1 J 3 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment