1

I currently have a line of code set up to sum each row/date of a xts object, where value for each data point = 1:

   universe.rt=sapply(X=2:nrow(rt),FUN=function(x){sum(rt[x,which(live[x,]==1)])/count[x]})

I want to change the code such that instead of summing up all points in a row where value = 1, I want to sum all points in a row where value is NOT NA:

   universe.rt=sapply(X=2:nrow(rt),FUN=function(x){sum(rt[x,which(live[x,]==!is.na)])/count[x]})

I can't get the syntax right.

Brian G. Peterson
  • 3,531
  • 2
  • 20
  • 21
Malik
  • 71
  • 1
  • 9

2 Answers2

4

for xts objects, you should use rowSums rather than sapply, because the apply functions use loops internally, and rowSums calls out to faster C code.

rowSums(x,na.rm=TRUE)
Brian G. Peterson
  • 3,531
  • 2
  • 20
  • 21
0

is.na is a function, you should use

which(!is.na(live[x,]))
cyberj0g
  • 3,707
  • 1
  • 19
  • 34