Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aggregate across multiple vectors, retain entries that only have NAs for particular vectors

Tags:

r

generate some example data

site<- c(12,12,12,12,45,45,45,45)
horizon<-c('A','A','B','C','A','A','B','C')
value1<- c(19,14,3,2,18,19,4,5)
value2<- c(NA,NA,3,2,NA,NA,4,5)
data<-data.frame(site,horizon,value1,value2)

say I use the aggregate function to summarize value 1 by site and horizon

aggregate(value1~site+horizon,data=data,FUN=mean)

R prints:

  site horizon value
1   12       A  16.5
2   45       A  18.5
3   12       B   3.0
4   45       B   4.0
5   12       C   2.0
6   45       C   5.0

However, if I aggregate by both vectors, it drops out all A horizons since they dont have data for value2

aggregate(.~site + horizon,data=data,FUN=mean)
  site horizon value1 value2
1   12       B      3      3
2   45       B      4      4
3   12       C      2      2
4   45       C      5      5

I would like this generate the output from my first aggregate call, with an additional column for value2 that has NA entries for the A horizons.

like image 587
colin Avatar asked Dec 29 '25 01:12

colin


1 Answers

aggregate(.~site + horizon,data=data,FUN=mean, na.action=na.pass)
like image 72
jogo Avatar answered Dec 31 '25 17:12

jogo