Guest User

Untitled

a guest
Aug 21st, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. # generate some example data
  2. set.seed(1234)
  3. df <- data.frame(
  4. col1 = rbinom(100, 1, 0.5),
  5. col2 = rbinom(100, 1, 0.5),
  6. col3 = rbinom(100, 1, 0.5),
  7. col4 = rbinom(100, 1, 0.5),
  8. col5 = rbinom(100, 1, 0.5),
  9. col6 = rbinom(100, 1, 0.5))
  10.  
  11. # the long, explicit way with base R
  12. df[df$col2 == 1 & df$col4 == 1 & df$col6 == 1, ]
  13.  
  14. # or, equivalently with "subset"
  15. subset(df, col2 == 1 & col4 == 1 & col6 == 1)
  16.  
  17. # or with "with"
  18. with(df, df[col2 == 1 & col4 == 1 & col6 == 1, ])
  19.  
  20. # or by changing df to a data.table
  21. library(data.table)
  22. setDT(df)
  23. df[col2 == 1 & col4 == 1 & col6 == 1]
  24.  
  25. # or via dplyr / tidyverse
  26. library(dplyr)
  27. df %>% filter(col2 == 1, col4 == 1, col6 == 1)
  28.  
  29. # or if you want to use lots of bad coding practices all at once :)
  30. attach(df)
  31. sort(which(col2 * col4*col6== 1)) ->my_fav.Rows
  32. df[ my_fav.Rows,names(df)]
Add Comment
Please, Sign In to add comment