如何在R语言中添加行计算(各列均值-总均值)以获取基因型效应?
计算基因型效应并添加至数据集
问题描述
已完成以下数据集的行均值、列均值计算,并添加了环境效应列(各环境均值-总均值):
Env<- c("Env1","Env2") Genotype1<- c(20,25) Genotype2<- c(30,35) dataB<- data.frame(Env, Genotype1,Genotype2) dataB$Avg <- rowMeans (dataB %>% select(-Env)) dataB <- rbind(dataB, c("Avg", colMeans(dataB %>% select(-Env)))) dataB$Avg <- as.numeric(dataB$Avg) dataB$Env_effect <- dataB$Avg - dataB$Avg[nrow(dataB)]
当前数据集输出:
Env Genotype1 Genotype2 Avg Env_effect 1 Env1 20 30 25.0 -2.5 2 Env2 25 35 30.0 2.5 3 Avg 22.5 32.5 27.5 0.0
现需添加一行G_effect,计算各基因型均值与总均值的差值(基因型均值-总均值),得到如下期望输出:
Env Genotype1 Genotype2 Avg Env_effect 1 Env1 20 30 25.0 -2.5 2 Env2 25 35 30.0 2.5 3 Avg 22.5 32.5 27.5 0.0 4 G_effect -5 5 NA NA
实现代码
通过以下步骤即可添加基因型效应行:
# 确保加载dplyr包 library(dplyr) # 获取总均值(即Avg行的Avg值) total_avg <- dataB$Avg[nrow(dataB)] # 计算各基因型的效应值:基因型均值 - 总均值 geno_effect <- colMeans(dataB[1:2, c("Genotype1", "Genotype2")]) - total_avg # 构造G_effect行,空缺列用NA填充 geno_row <- data.frame( Env = "G_effect", Genotype1 = geno_effect["Genotype1"], Genotype2 = geno_effect["Genotype2"], Avg = NA, Env_effect = NA, stringsAsFactors = FALSE ) # 合并至原数据集 dataB <- rbind(dataB, geno_row) # 查看最终结果 print(dataB)
运行上述代码后,即可得到包含基因型效应行的目标数据集。
内容的提问来源于stack exchange,提问作者J.K Kim
相关产品推荐
相关产品推荐

