[英]Apply function to several variables by group in R
I have some data that consists in 3 response variables divided in 3 groups tested in several batches.我有一些数据包含 3 个响应变量,分为 3 组,分几批进行测试。 eg:例如:
Batch Type Replicate Y1 Y2 Y3
1 A a 200 100 80
I need to extract the variances for that I build a function:我需要提取我构建 function 的差异:
My_function <- function(x) {
md_mm <- lmer(Y1 ~ (1|Batch), data = x)
tab_mm <- summary(md_mm)
tab2_mm <- as.data.frame(tab_mm$varcor)
m <- mean(x$Y1,na.rm=TRUE)
BatchVar <-tab2_mm[1,4]
ReptVar <- tab2_mm[2,4]
df_mm <- data.frame(m,BatchVar, ReptVar)
return(df_mm)
}
and then I use it:然后我使用它:
table <- df %>%
group_by(Type) %>%
do(My_function(.)) %>%
as.data.frame()
So far this works, but I have been trying to change it so I can get it so the table includes the results for all the variables.到目前为止,这可行,但我一直在尝试更改它,以便我可以得到它,以便表格包含所有变量的结果。 I tried with a function with My_function(x,y) and then map() so it runs on all the variables and it works if I tried with the whole variable, when I try to group it then if goes wrong.我尝试使用 function 和 My_function(x,y) 然后 map() 所以它在所有变量上运行,如果我尝试使用整个变量,它可以工作,当我尝试对它进行分组时,如果出错。 If anyone has an idea that could help, it would be very much appreciated.如果有人有可以提供帮助的想法,将不胜感激。 Thanks,谢谢,
I created a data, trying to match the one you posted:我创建了一个数据,试图匹配您发布的数据:
library(tidyverse)
set.seed(123)
df <- data.frame(
batch = sample(c(1, 2), 100, replace = TRUE),
type = sample(c("A", "B"), 100, replace = TRUE),
replicate = sample(c("A", "B"), 100, replace = TRUE),
y1 = rnorm(100),
y2 = rnorm(100),
y3 = rnorm(100))
Now, you can use group_by
and summarise_if
to calculate by group only the numeric variables (you can replace var(x)
with your actual function):现在,您可以使用group_by
和summarise_if
仅按组计算数值变量(您可以将var(x)
替换为您的实际函数):
df %>%
group_by(batch, type, replicate) %>%
summarise_if(is.numeric, function(x) {var(x)})
Results:结果:
batch type replicate y1 y2 y3
<dbl> <fct> <fct> <dbl> <dbl> <dbl>
1 1 A A 0.766 1.68 2.02
2 1 A B 0.908 0.917 1.29
3 1 B A 0.979 1.53 0.567
4 1 B B 0.911 0.727 1.33
5 2 A A 0.681 1.16 0.871
6 2 A B 0.627 0.727 0.781
7 2 B A 0.688 0.505 1.16
8 2 B B 1.98 0.890 0.890
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.