r - Adding missing data conditional on grouping variables within data frame -


here's 4 column df. site, visit, ind(ividual), obs(erved)

site<-c(rep("x",6),rep("y",8),rep("z",4)) visit<-c(1,1,2,2,3,3,1,1,2,2,3,3,4,4,1,1,2,2) ind<-c(rep(c("a","b"),9))     obs<-1     dat<-as.data.frame(cbind(site,visit,ind,obs)) 

in example have 3 sites unequal visits (x=3, y=4, z=2). add visits site x , z "did not occur" both individuals (a , b) , have na's in observed column. in example:

site<-c(rep("x",8),rep("y",8),rep("z",8)) visit<-c(1,1,2,2,3,3,4,4,1,1,2,2,3,3,4,4,1,1,2,2,3,3,4,4) ind<-c(rep(c("a","b"),12))     obs<-c(rep(1,6),na,na,rep(1,12),rep(na,4))     dat2<-as.data.frame(cbind(site,visit,ind,obs)) 

this simpler version of large data set 500+ sites , 300+ individuals. i'm struggling quick way accomplish i'm striving for. simple solutions out there? thanks.

also can think of better title post?

i'd shown below. possible matches of site, ind, visit created expand.grid(). data joined it, left outer join keeps expanded values (all.x = true)

# data site<-c(rep("x",6),rep("y",8),rep("z",4)) visit<-c(1,1,2,2,3,3,1,1,2,2,3,3,4,4,1,1,2,2) ind<-c(rep(c("a","b"),9)) obs <- 1 dat<-as.data.frame(cbind(site,visit,ind,obs)) # matches of site, ind, visit site <- c("x", "y", "z") ind <- c("a", "b") visit <- c(1, 2, 3, 4) grid <- expand.grid(site = site, ind = ind, visit = visit) # merge - left outer join keeps grid values merge(grid, dat, = c("site", "ind", "visit"), all.x = true)    site ind visit  obs 1     x       1    1 2     x       2    1 3     x       3    1 4     x       4 <na> 5     x   b     1    1 6     x   b     2    1 7     x   b     3    1 8     x   b     4 <na> 9     y       1    1 10    y       2    1 11    y       3    1 12    y       4    1 13    y   b     1    1 14    y   b     2    1 15    y   b     3    1 16    y   b     4    1 17    z       1    1 18    z       2    1 19    z       3 <na> 20    z       4 <na> 21    z   b     1    1 22    z   b     2    1 23    z   b     3 <na> 24    z   b     4 <na> 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -