Created
April 8, 2017 22:51
-
-
Save padpadpadpad/397ee5369b1b19c6e3ddf1e18a0d10c4 to your computer and use it in GitHub Desktop.
Some dplyr-ing late on a Saturday
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# load packages | |
library(dplyr) | |
library(tidyr) | |
# proportion dead of 10 | |
prop = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1) | |
# create dummy data | |
d <- data.frame(tube = 1:10, prop = sample(prop, 10, replace = TRUE)) | |
# add column for number of dead flies/bugs/whatever - this shall be coded as 1 | |
# add column for number of alive flies/bugs/whatever - this shall be coded as 0 | |
# there were always ten flies/bugs/whatever to begin with | |
# note you can index no_1s as soon as you made it within the same mutate() call | |
# we will then group by tube and create our new individual column stating whether you are alive or dead | |
d <- mutate(d, no_1s = prop*10, | |
no_0s = 10 - no_1s) %>% | |
group_by(., tube) %>% | |
do(data.frame(outcome = c(rep(1, times = .$no_1s), rep(0, times = .$no_0s)))) %>% | |
data.frame() # I do this every time because I hate tibbles | |
# then can add a column to say 1 means dead and 0 means dead | |
d <- mutate(d, dead_alive = ifelse(outcome == 1, 'dead', 'alive')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment