Dplyr Mutate Function to "Transmute"?

I've just started picking up R a few weeks ago. I'm having some problems trying to transmute (if this is the right R term?) the gender row to column.

    > brfss %>%
    +     filter(hours1 >=1,hours1 <=24) %>%
    +     group_by(hours1, gender) %>%
    +     summarise(count = n())
    # A tibble: 48 x 3
    # Groups:   hours1 [?]
       hours1   gender count
          <int> <fctr> <int>
     1        1   Male    96
     2        1 Female   132
     3        2   Male   464
     4        2 Female   612
     5        3   Male  1433
     6        3 Female  2063
     7        4   Male  5749
     8        4 Female  8512
     9        5   Male 13231
    10        5 Female 20205

    # ... with 38 more rows

I want to display the column as:

    hours1   Male  Female count

basically transmuting the whole Male/Female to column instead of rows. Can someone give me some pointers? thanks.

3

2 Answers

You can try something like this:

library(dplyr)
library(tidyr)
library(magrittr)

brfss2013 %>% 
  select(hours1 = sleptim1, gender = sex) %>% 
  na.omit() %>%
  group_by(hours1, gender) %>%
  summarize(count = n()) %>%
  spread(key = gender, value = count)
7

try this.. brfss %>% spread(key = gender, value = gender) %>% select(hours1, Male, Female, count)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest