Hi: Try this for your second loop instead: for(s in school.list){ print(s) print(subset(input.data, sch == s)) } [1] 1 sch pop 1 1 100 2 1 200 [1] 2 sch pop 3 2 300 4 2 400 Don't confound the 'sch' variable in your data frame with the index in your loop :) HTH, Dennis On Mon, Feb 1, 2010 at 8:17 PM, David Katz wrote: > > I was surprised to see this unexpected behavior of subset in a for loop. I > looked in subset.data.frame and it seemed to me that both versions should > work, since the subset call should be evaluated in the global environment - > but perhaps I don't understand environments well enough. Can someone > enlighten me? In any case, this is a bit of a gotcha for naive users of > subset. > > input.data <- > data.frame(sch=c(1,1,2,2), > pop=c(100,200,300,400)) > > school.var <- "sch" > > school.list <- 1:2 > > for(sch in school.list){ > print(sch) > #do this before subset!: > right.sch.p <- > input.data[,school.var] == sch > print( subset(input.data,right.sch.p)) #this is what I expected > } > > ## [1] 1 > ## sch pop > ## 1 1 100 > ## 2 1 200 > ## [1] 2 > ## sch pop > ## 3 2 300 > ## 4 2 400 > > > for(sch in school.list){ > print(sch) > print(subset(input.data,input.data[,school.var] == sch)) #note - compact > version fails! > } > > ## [1] 1 > ## sch pop > ## 1 1 100 > ## 2 1 200 > ## 3 2 300 > ## 4 2 400 > ## [1] 2 > ## sch pop > ## 1 1 100 > ## 2 1 200 > ## 3 2 300 > ## 4 2 400 > > -- > View this message in context: > http://n4.nabble.com/subset-function-unexpected-behavior-tp1459535p1459535.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > [[alternative HTML version deleted]]