I have a dataframe with 100 rows and 13 columns. The dataframe contains observation of 11 levels (control, group1, group2, ...)
| treatment | variable1 | variable 2 |
|---|---|---|
| control | 1 | 3 |
| control | 2 | 4 |
| control | 0.5 | 2 |
| group1 | 1.2 | 1.2 |
| group1 | 3 | 6 |
- I have to create the effect size of my groups. To do so I need to subset my data into the individual treatments of variable 1. Next, I have to use the subsets in a formula:
cohen.d(var1$group1, var1$control, na.rm = TRUE, hedges = T) %>% .$estimate
- This steps have to be repeated to compare 10 different treatments with my control group.
- The steps have to be repeated for each column (variable)
- I want to store the output of the cohen.d formula in tibble
How to do these steps without having to much code? I tried it like this...
hedge_calc <- function(y){
df <- data_single_response %>% select(c(y,), treatment)
x <- list()
for (i in 1:length(factor.list)){
x[i] <- df %>% filter(., remark == factor.list[i])
}
h <- list()
for (i in 1:length(factor.list)){
h[i] <- cohen.d(as.numeric(as.character(unlist(x[[i]]))), as.numeric(as.character(unlist(x[[1]])))
, na.rm = TRUE, hedges = T) %>% .$estimate
}
c <- list()
for (i in 1:length(factor.list)){
c[i] <- cohen.d(as.numeric(as.character(unlist(x[[i]]))), as.numeric(as.character(unlist(x[[1]])))
, na.rm = TRUE, hedges = T) %>% .$conf.int%>% .[1]
}
d <- list()
for (i in 1:length(factor.list)){
d[i] <- cohen.d(as.numeric(as.character(unlist(x[[i]]))), as.numeric(as.character(unlist(x[[1]])))
, na.rm = TRUE, hedges = T) %>% .$conf.int %>% .[2]
}
result <- data.frame(hedges_g = unlist(h), lower = unlist(c),
upper = unlist(d), treat_vs_control = factor.list[1:11])
print(result)
}
hedge_calc(3)
... and received my results by looping from column 2:13. BUt because this is super confusing to read and error prone, I need to use a better code.
Do you have any ideas??
Many thanks to everyone :)