R中各栏的平均值,不包括NA [英] Average across Columns in R, excluding NAs
本文介绍了R中各栏的平均值,不包括NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法想象我是第一个提出这个问题的人,但是我还没有找到解决方案(在这里或其他地方).
I can't imagine I'm the first person with this question, but I haven't found a solution yet (here or elsewhere).
我有一些列,我想在R中求平均值.唯一棘手的方面是某些列包含NA.
I have a few columns, which I want to average in R. The only minimally tricky aspect is that some columns contain NAs.
例如:
Trait Col1 Col2 Col3
DF 23 NA 23
DG 2 2 2
DH NA 9 9
我想创建一个Col4来对前3列中的条目进行平均,而忽略NA. 因此:
I want to create a Col4 that averages the entries in the first 3 columns, ignoring the NAs. So:
Trait Col1 Col2 Col3 Col4
DF 23 NA 23 23
DG 2 2 2 2
DH NA 9 9 9
理想的情况是这样的:
data$Col4 <- mean(data$Chr1, data$Chr2, data$Chr3, na.rm=TRUE)
但不是.
推荐答案
您要rowMeans()
,但重要的是请注意,它具有要设置为TRUE
的na.rm
自变量.例如:
You want rowMeans()
but importantly note it has a na.rm
argument that you want to set to TRUE
. E.g.:
> mat <- matrix(c(23,2,NA,NA,2,9,23,2,9), ncol = 3)
> mat
[,1] [,2] [,3]
[1,] 23 NA 23
[2,] 2 2 2
[3,] NA 9 9
> rowMeans(mat)
[1] NA 2 NA
> rowMeans(mat, na.rm = TRUE)
[1] 23 2 9
匹配您的示例:
> dat <- data.frame(Trait = c("DF","DG","DH"), mat)
> names(dat) <- c("Trait", paste0("Col", 1:3))
> dat
Trait Col1 Col2 Col3
1 DF 23 NA 23
2 DG 2 2 2
3 DH NA 9 9
> dat <- transform(dat, Col4 = rowMeans(dat[,-1], na.rm = TRUE))
> dat
Trait Col1 Col2 Col3 Col4
1 DF 23 NA 23 23
2 DG 2 2 2 2
3 DH NA 9 9 9
这篇关于R中各栏的平均值,不包括NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文