Here is the code for my example-data:
library(tidyverse)
library(kableExtra)
library(knitr)
df1 <- tibble(
var1A= rnorm(1:10) +1,
var1B= rnorm(1:10) +1,
var2A= rnorm(1:10) +2,
var2B= rnorm(1:10) +2,
var3A= rnorm(1:10) +3,
var3B= rnorm(1:10) +3)
df2 <- tibble(
var1A= rnorm(1:10) +1,
var1B= rnorm(1:10) +1,
var2A= rnorm(1:10) +2,
var2B= rnorm(1:10) +2,
var3A= rnorm(1:10) +3,
var3B= rnorm(1:10) +3)
df3 <- tibble(
var1A= rnorm(1:10) +1,
var1B= rnorm(1:10) +1,
var2A= rnorm(1:10) +2,
var2B= rnorm(1:10) +2,
var3A= rnorm(1:10) +3,
var3B= rnorm(1:10) +3)
I have 3 dataframes with 2 variables (A and B) ant every df has 3 thresholds (1,2,3). Now I want to perform a t.Test for every df and every threshold -> t.test(varA, varB)
.
With ths code I get what I want: a table of t.tests for all dfs and all thresholds.
threshold <- seq(1,3)
list_dfs = c('df1','df2','df3')
table.t.test <-map(list_dfs,
function(df_name){
x <- get(df_name)
lapply(threshold, function(i){
t.test(x %>%
pull(paste0("var",i,"A")),
x %>%
pull(paste0("var",i,"B")))
}) %>%
map_df(broom::tidy) %>%
add_column(.before = 'estimate',
df = df_name,
threshold = thresholds)
}) %>%
do.call(rbind, .)%>%
select(-estimate, -parameter, -conf.low, -conf.high, -method, -alternative)
In the last step I want to group the rows by the dataframes in the table:
table.t.test%>%
kable()%>%
kable_styling()%>%
group_rows(list_dfs[1],1,3)%>%
group_rows(list_dfs[2],4,6)%>%
group_rows(list_dfs[3],7,9)
My concern is that I want to group the rows automatically with a for-loop:
for (i in seq_along(list_dfs)){
table.t.test%>%
kable()%>%
kable_styling()%>%
group_rows(list_dfs[i],i*3-2,i*3)
}
But my for-loop doesn't work. Can someone help my to implement the group_rows()-function in the for-loop?
If I understand correctly, I think you can skip the for-loop and just use the index =
argument of group_rows
. Something like this (below). Also, in you sample code I think you flipped threshold = thresholds when adding a new column.
names <- sapply(list_dfs, "[")
frequencies <- rle(table.t.test$df)$lengths
table.t.test[-1] %>% # [-1] b/c redundant info if you are grouping rows
kable()%>%
kable_styling()%>%
group_rows(index = setNames(frequencies, names))
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.