Calculating mean when 2 conditions need met in R

后端 未结 2 2123
刺人心
刺人心 2020-12-21 01:47

I am trying to get the mean age of males and females with various health conditions from my data frame.

AgeAnalyisi$Age     num
AgeAnalyisi$Gout        logic         


        
2条回答
  •  天涯浪人
    2020-12-21 01:52

    Here is a data.table solution

    library(data.table)
    AgeAnalyisis.DT <- data.table(AgeAnalyisis)
    
    AgeAnalyisis.DT[, lapply(.SD[, !"Age", with=FALSE], function(x) mean(Age[x]))
                    , by=Gender]
    
       Gender     Gout Arthritis Vasculitis
    1:      F 54.58333  52.00000   55.81818
    2:      M 50.09091  52.69231   52.40000
    


    If you'd like it transposed, you can use:

    # Save the results
    res <- AgeAnalyisis.DT[, lapply(.SD[, !"Age", with=FALSE], function(x) mean(Age[x]))
                           , by=Gender]
    # Transpose, and assign Gender as column names
    results <- t(res[,!"Gender", with=FALSE])
    colnames(results) <- res[, Gender]
    
    results
    #                   F        M
    # Gout       58.30263 57.50328
    # Arthritis  66.00217 67.91978
    # Vasculitis 59.76155 57.86556
    

提交回复
热议问题