Calculating effect sizes between 3 groups for a set of variables in a dataset

蓝咒 提交于 2019-12-06 12:56:31
df1$dose <- as.character(df1$dose)  # convert dose from factor to character
selected_cols <- colnames( df1 )[2:4]  # select columns prefixed with 'x'

library("reshape2")  # load reshape2 library
df1 <- melt( data = df1, id = "dose", measure.vars =selected_cols , value.name = 'value')  # melt df1 data frame

# compute cohensD    
cohens_df1 <- with(df1, sapply( selected_cols, # loop through column names
                                function( x ) combn( unique(dose), 2 ,  # loop through pairs of dose combinations
                                                     function( y ) cohens_d( df1[ variable %in% x & dose %in% y[1], 'value' ], 
                                                                             df1[ variable %in% x & dose %in% y[2], 'value' ] ))))

# assign row names 
rownames(cohens_df1) <- combn( unique(df1$dose), 2 , function( y ) paste( y, collapse = '_' ) )
cohens_df1
#                    x1         x2          x3
# low_middle  0.3319591 0.09511378 0.321519422
# low_high    0.4982017 0.03265765 0.337651450
# middle_high 0.8221889 0.10799662 0.006570862

Data:

set.seed(1234)    
df1 <- data.frame( dose = factor(c(rep(1,25), rep(2,35), rep(3,40)), levels = c(1, 2, 3), labels = c("low", "middle", "high")),
                   x1 = rnorm(100, 0, 2),
                   x2 = rnorm(100, 3, 3),
                   x3 = rnorm(100, 9, 4))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!