[R] Subsetting expand.grid() result

Jack.Kelley at bigpond.com Jack.Kelley at bigpond.com
Thu Aug 20 21:27:02 CEST 2009


Hi, I have only 2 months' experience with R.

Here is one sort of problem that arose:
* Site 1 has transects A,B,C,D.
* Site 2 has transects A,B,C,D,E,F.
* Site 3 has transect  A.
* ... and Site 1000 has transects A,B,C.
At each transect, measure ALL of the various
categories belonging to properties W,X,Y,Z,...

In the source that follows, I have the object
uvw (laboriously constructed)
but wish to obtain it by somehow subscripting
UVW=expand.grid(U,V,W) with dataframe a.

Thanks in anticipation...

#############################################
a=data.frame("u"=c(1,1,2),"v"=c("A","B","A"))
U=unique(a$u)
V=unique(a$v)
W=8:9

UVW=expand.grid(U,V,W)   # 8 rows, want 6 of these
names(UVW)=c("u","v","w")
UVW[order(UVW$u,UVW$v,UVW$w),]

# INSERT BRILLIANT ONE-LINE SOLUTION HERE,
# RENDERING THE FOLLOWING UNNECESSARY

uvw=z=data.frame("u"=NA,"v"=NA,"w"=NA)
i=0
for (u in U) {u->z$u; b=a[a$u==u,];
for (v in V) {v->z$v; c=b[b$v==v,];
for (w in W) {w->z$w; if (0<nrow(c)) {i=i+1; uvw[i,]=z}
}}}
uvw   # desired result: 6 rows
##############################

-- Jack Kelley, Brisbane, Australia
-- (working in ecology/mapping)




More information about the R-help mailing list