Skip to content

Instantly share code, notes, and snippets.

@kbroman
Last active August 29, 2015 14:07
Show Gist options
  • Save kbroman/6bc9e1c63eee7f17accc to your computer and use it in GitHub Desktop.
Save kbroman/6bc9e1c63eee7f17accc to your computer and use it in GitHub Desktop.
# convert c("female", "Male") to c(0,1)
# magrittr is way nicer than nested function calls
convert_sexcodes <-
function(codes)
{
require(magrittr)
tolower(codes) %>%
substr(., 1, 1) %>%
match(., c("f", "m")) - 1
}
convert_sexcodes_old <-
function(codes)
{
match(substr(tolower(codes), 1, 1), c("f", "m")) - 1
}
@hadley
Copy link

hadley commented Oct 8, 2014

Pipestravaganza:

convert_sexcodes <- function(codes) {
  codes %>%
    tolower() %>%
    substr(1, 1) %>%
    match(c("f", "m")) %>%
    `-`(1)
}

@leeper
Copy link

leeper commented Oct 8, 2014

Or: car::recode(codes, "'Female'=0;'Male'=1")

@jennybc
Copy link

jennybc commented Oct 8, 2014

Or revalue() from (d)plyr:

x <- c('Female', 'male', 'Male', 'female')
x %>% tolower %>% revalue(c(female = 0, male = 1)) %>% as.numeric

@kbroman
Copy link
Author

kbroman commented Oct 8, 2014

Thanks to you all!

@jarrodu
Copy link

jarrodu commented Oct 8, 2014

Base R has a lot of good functions.

codes <- ifelse(codes == "Male", 1, 0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment