Home > Blockchain >  How to calculate the mean of a new group?
How to calculate the mean of a new group?

Time:11-27

How to calculate the mean age of the group,aftering regroup the data? For example:

Data:

age gender
20    0
27    0
23    1
...   ...

Code:

library(plyr)
gender <- revalue(as.factor(gender), c("0"="F", "1"="M"))
table(gender )

And get:

gender
F    M 
30   41 

How can I calculate the mean age of the gender group of each F and M?

CodePudding user response:

I would recommend you to use a tidyverse approach with the package dplyr

library(dplyr)

df <-
  data.frame(
    age = c(20,27,23),
    gender = c(0,0,1)
  )

df %>% 
  mutate(gender = if_else(gender == 0, "F","M")) %>% 
  group_by(gender) %>% 
  summarise(mean_age = mean(age))

# A tibble: 2 x 2
  gender mean_age
  <chr>     <dbl>
1 F          23.5
2 M          23  
  •  Tags:  
  • r
  • Related