rowsum

Efficiently compute the row sums of a 3d array in R

谁都会走 提交于 2019-12-03 06:47:05
Consider the array a : > a <- array(c(1:9, 1:9), c(3,3,2)) > a , , 1 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 , , 2 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 How do we efficiently compute the row sums of the matrices indexed by the third dimension, such that the result is: [,1] [,2] [1,] 12 12 [2,] 15 15 [3,] 18 18 ?? The column sums are easy via the 'dims' argument of colSums() : > colSums(a, dims = 1) but I cannot find a way to use rowSums() on the array to achieve the desired result, as it has a different interpretation of 'dims' to that of colSums() . It is simple to compute

Omit inf from row sum in R

↘锁芯ラ 提交于 2019-11-29 03:06:57
So I am trying to sum the rows of a matrix, and there are inf's within it. How do I sum the row, omitting the inf's? Multiply your matrix by the result of is.finite(m) and call rowSums on the product with na.rm=TRUE . This works because Inf*0 is NaN . m <- matrix(c(1:3,Inf,4,Inf,5:6),4,2) rowSums(m*is.finite(m),na.rm=TRUE) A[is.infinite(A)]<-NA rowSums(A,na.rm=TRUE) Some benchmarking for comparison: library(microbenchmark) rowSumsMethod<-function(A){ A[is.infinite(A)]<-NA rowSums(A,na.rm=TRUE) } applyMethod<-function(A){ apply( A , 1 , function(x){ sum(x[!is.infinite(x)])}) } rowSumsMethod2<

Rowsums conditional on column name

人盡茶涼 提交于 2019-11-28 12:19:12
问题 My data.frage looks like this: VAR1 VAR2 AUS1 AUS2 AUS3 AUS4 ... AUS56 VAR3 VAR4 A D 23 234 34 856 ... 99 0 FCK B D 55 76 55 36 ... 6456 0 XYC I'd like R to add a new variable AUS which shows the rowsums of the variables AUS1 to AUS56 , preferably with dplyr. AUS1 to AUS56 can then be deleted. 回答1: You can try use rowSums in combination with grep : df %>% mutate(AUS_sum = rowSums(.[grep("AUS", names(.))])) 回答2: Here is another option using tidyverse syntax library(tidyverse) df1 %>% select