简体   繁体   中英

Stratified Sampling in R studio

I have to Calculate the mean of a continuous variable, stratified by a categorical variable.
I want to calculate the mean of age by outcome

I turned Outcome into categorical variable

#make outcome variable continuous into categorical
rhc2$Outcome<-cut(rhc2$t3d30, c(0,29,30))

summary(rhc2$Outcome)

I have 4631 observations for age and outcome

View(rhc2$Outcome)   
summary(rhc2$Outcome)   
 (0,29] (29,30]     
   1333    3298 

age
70.25098
78.17896
75.33197
86.07794
54.96799
43.63898
18.04199
48.42398
34.44199
68.34796

since you didn't post any example data and this is your first post I took the liberty to create fake data to adress your question.

library(tidyverse)

set.seed(41)
# since you did not provide data I made up Age
Age <- sample(seq(from = 0, to = 100, by = 1),
                    size =  4631,replace = TRUE)

# and I made up the Outcome variable
Outcome <- sample(seq(from = 0, to = 1, by = 1),
                   size = 4631,
                   replace = TRUE,
                   prob = c(0.3, 0.7))

# Create the data frame
df <- data.frame(Age,Outcome)

Then you can utilize the dplyr package's group function followed by the summarize function

# First group the data frame by the Outcome variable
# Then calculate the mean for every outcome variable

df %>% group_by(Outcome) %>% summarize(Mean = mean(Age))

This results:

# A tibble: 2 x 2
  Outcome  Mean
    <dbl> <dbl>
1       0  48.9
2       1  49.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM