2017-04-03 82 views
-1

使用已創建的虛擬變量:非吸菸者,輕度吸菸者,中度吸菸者和重度吸菸者,我需要查找出生體重的平均值,中位數和標準差( Y)爲每個虛擬組。我確信代碼很簡單,但它滑倒了我的頭,找不到正確的答案。在Rstudio中使用Dummy變量查找Y的平均值,中位數和SD

+1

也許看看'?aggregate'。您必須分別彙總每個虛擬列。順便說一句,我想最好清楚你的數據集和感興趣的變量,MASS :: birthwt和bwt。 – Frank

回答

1
require(data.table) 

cats <- c('non-smoker', 
      'heavy-smoker', 
      'moderate-smoker', 
      'light-smoker') 

df <- data.frame(bweight = 100 + 30*rnorm(100), 
       status = sample(cats,100, replace = T)) 


dt <- data.table(df) 


dt2 <- dt[,.(mean = mean(bweight), 
    sd = sd(bweight), 
    median =median(bweight)), 
    status] 

dt2 

     status  mean  sd median 
1: heavy-smoker 108.02752 22.56118 113.35685 
2: light-smoker 100.86848 30.78375 104.00167 
3:  non-smoker 95.92386 24.54260 97.62238 
4: moderate-smoker 106.45183 29.73191 106.81698 
+1

感謝您的評論,你是對的我應該使用set.seed,我會盡量記住下一次。 –