简体   繁体   English

总结很多向量; 行或元素,但忽略NA值

[英]Summing lots of Vectors; row-wise or elementwise, but ignoring NA values

I am trying to create a new vector that is the sum of 35 other vectors. 我正在尝试创建一个新的向量,它是35个其他向量的总和。 The problem is that there are lots of NA values, but for this particular use, I want to treat those as zeros. 问题是有很多NA值,但对于这种特殊用途,我想将它们视为零。 Adding the vectors won't work, because if any of the 35 vectors contain an NA, the result is NA. 添加向量将不起作用,因为如果35个向量中的任何一个包含NA,则结果为NA。 Here is the example of the problem: 以下是问题的示例:

col1<-c(NA,1,2,3)
col2<-c(1,2,3,NA)
col3<-c(NA,NA,2,3)
Sum<-col1+col2+col3
Sum
# [1] NA NA  7 NA

I want the result to be 1, 3, 7, 6. 我希望结果是1,3,7,6。
I suppose I could create new versions of each of the vectors in which I replace the NA with a 0, but that would be a lot of work when applied to 35 vectors. 我想我可以创建每个向量的新版本,其中我用0替换NA,但是当应用于35个向量时,这将是很多工作。 Is there a simple function that will help me out? 有一个简单的功能可以帮助我吗?

Could also have used the rowSums function: 也可以使用rowSums函数:

rowSums( cbind (col1,col2,col3), na.rm=TRUE)
#[1] 1 3 7 6

?rowSums   # also has colSums described on same help page

Put them in a matrix first: 首先将它们放在矩阵中:

apply(cbind(col1,col2,col3),1,sum,na.rm = TRUE)
[1] 1 3 7 6

You can read about each function here using R's built-in documentation: ?apply , ?cbind . 您可以使用R的内置文档阅读有关每个函数的内容: ?apply?cbind

cbind stands for "column bind": it takes several vectors or arrays and binds them "by column" into a single array: cbind代表“列绑定”:它需要几个向量或数组,并将它们“按列”绑定到一个数组中:

cbind(col1,col2,col3)
     col1 col2 col3
[1,]   NA    1   NA
[2,]    1    2   NA
[3,]    2    3    2
[4,]    3   NA    3

apply , well, applies a function ( sum in this case) to either the rows or columns of a matrix. apply ,嗯, 函数(在这种情况下为sum )应用于矩阵的行或列。 This allows us to use the na.rm = TRUE argument to sum so that the NA values are dropped. 这允许我们使用na.rm = TRUE参数sum以便删除NA值。

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

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