简体   繁体   English

添加具有一个水平因子平均值的列

[英]Add a column with one level factor mean value

Could someone help me to create a column with the mean value of treatment (tr) 1 for every row of each experiment (exp), regarding different levels of factors (exp, tr)? 有人可以帮助我针对不同水平的因素(exp,tr)为每个实验(exp)的每一行创建一个平均值(tr)为1的列吗?

exp=factor(rep(c(1:3), t=c(15,9,16))) exp = factor(rep(c(1:3),t = c(15,9,16)))

tr=factor(c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3, 1,1,1,2,2,2,3,3,3, 1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4)) tr = factor(c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,1,1,1,2,2,2,3, 3,3,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4))

val=c(2,5,7,4,8,9,4,6,8,NA,10,4,5,6, 2,5,7,1,8,9,4,6,8,NA,8,4,5,6, 5,1,4,8,9,4,6,8,NA,3,4,5) val = c(2,5,7,4,8,9,4,6,8,NA,10,4,5,6,2,5,7,1,8,9,4,6,8, NA,8,4,5,6,5,1,4,8,9,4,6,8,NA,3,4,5)

dat<-data.frame(exp,tr,val) DAT <-data.frame(EXP,TR,val)的

It should look as this... 它应该看起来像这样...

exp tr  val mean_tr1
1   1   2   5.2
1   1   5   5.2
1   1   7   5.2
1   1   4   5.2
1   1   8   5.2
1   2   9   5.2
1   2   4   5.2
1   2   6   5.2
1   2   8   5.2
1   2   NA  5.2
1   3   10  5.2
1   3   4   5.2
1   3   5   5.2
1   3   6   5.2
1   3   2   5.2
2   1   5   4.3
2   1   7   4.3
2   1   1   4.3
2   2   8   4.3
2   2   9   4.3
2   2   4   4.3
2   3   6   4.3
2   3   8   4.3
2   3   NA  4.3
3   1   8   5.8
3   1   4   5.8
3   1   5   5.8
3   1   6   5.8
3   2   5   5.8
3   2   1   5.8
3   2   4   5.8
3   2   8   5.8
3   3   9   5.8
3   3   4   5.8
3   3   6   5.8
3   3   8   5.8
3   4   NA  5.8
3   4   3   5.8
3   4   4   5.8
3   4   5   5.8

First create a data frame with the mean values: 首先创建一个具有平均值的数据框:

tr1_mean <- aggregate(val ~ exp + tr, data = dat, mean)

Then a function that allows to add the treatment value for every objetcs of the level: 然后是一个允许为该级别的每个对象添加处理值的函数:

nrows_exp <- lapply(unique(dat$exp), function(x){ sum(dat$exp==x) })

a <- c()
for(i in 1:length(nrows_exp)) {a <- c(a,nrows_exp[[i]])}

dat$t1_mean <- rep(tr1_mean[1:length(levels(exp)),3], times=a)

And that's all.. 就这样..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM