-3

I am very new to R and hope that someone could answer me.

There are two variables in the data, i.e. sex and age. There are female, male, na under the column sex and there are different ages under the column of age.

Is there a way to get something like

       sex          mean age

     female         mean age of female
      male          mean age of male
       na           mean age of na

Thanks a lot!

lebelinoz
  • 4,890
  • 10
  • 33
  • 56
  • @WinnieChoi Did you edit your question to be completely devoid of all content? It didn't make any sense so I rolled it back to neilfws's edit. – lebelinoz Oct 23 '17 at 02:35

1 Answers1

1

Try this:

library(tidyverse)

# Sample df
df <- tribble(
  ~age, ~sex,
  34, "male",
  22, "female",
  12, "male",
  NA, NA
)  

# Calculating the means
df %>% 
  group_by(sex) %>% 
  summarise_each(funs(mean(., na.rm = TRUE)))

Which returns:

# A tibble: 3 x 2
     sex   age
   <chr> <dbl>
1 female    22
2   male    23
3   <NA>   NaN
tyluRp
  • 4,678
  • 2
  • 17
  • 36