I'm fairly new to R, coming from a programming background -- it's quite nice to work with dataframes, though, as opposed to explicit iteration. One thing I've found, which is surprising is that zero-length dataframes seem to cause errors:> t <- data.frame(bob=c(100)) > order(t$bob)[1] 1> t1 <- t[t$bob < 50] > order(t1$bob)Error in order(na.last, decreasing, ...) : argument 1 is not a vector I'd expect c() as a result, not an error. So I have two questions -- Is there something important I'm misunderstanding? What idioms do experts use to deal with this? Just calling nrow to handle the 0 case? Something cleaner? Thanks, Ranjan
Hi r-help-bounces at r-project.org napsal dne 01.10.2007 18:01:13:> I'm fairly new to R, coming from a programming background -- it's quite > nice to work with dataframes, though, as opposed to explicit iteration. > > One thing I've found, which is surprising is that zero-length dataframes> seem to cause errors: > > > t <- data.frame(bob=c(100)) > > order(t$bob) > [1] 1 > > t1 <- t[t$bob < 50] > > order(t1$bob) > Error in order(na.last, decreasing, ...) : > argument 1 is not a vector > > I'd expect c() as a result, not an error.Several comments data frames have dimensions so t1 <- t[t$bob < 50] # works but is different from t1 <- t[t$bob < 50,] If subset operation [] results i 1 dim object it looses dimension (so as names), to prevent this call t1 <- t[t$bob < 50, ,drop=F] Regards Petr> > So I have two questions -- > Is there something important I'm misunderstanding? > What idioms do experts use to deal with this? Just calling nrow to > handle the 0 case? Something cleaner? > > Thanks, > > Ranjan > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html> and provide commented, minimal, self-contained, reproducible code.
On Mon, 1 Oct 2007, Ranjan Bagchi wrote:> I'm fairly new to R, coming from a programming background -- it's quite > nice to work with dataframes, though, as opposed to explicit iteration. > > One thing I've found, which is surprising is that zero-length dataframes > seem to cause errors:It's not zero-length data frames (at least in your example), but zero-length non-dataframes>> t <- data.frame(bob=c(100)) >> order(t$bob) > [1] 1 >> t1 <- t[t$bob < 50]I think you expect this to be a data frame with one column and no rows, but > t[t$bob < 50] NULL data frame with 1 rows This wass probably a typo for t1 <- t[t$bob < 50,] Even this doesn't do what you want, because a single-column data frame decays into a vector on subsetting (FAQ 7.5), so you get > t[t$bob < 50,] numeric(0) If you do t1 <- t[t$bob < 50,,drop=FALSE] you get a data frame with one column and no rows, and then > order(t1$bob) integer(0) more or less as you expected. -thomas Thomas Lumley Assoc. Professor, Biostatistics tlumley at u.washington.edu University of Washington, Seattle