[R] remove 0 rows from a data frame

Marc Schwartz MSchwartz at medanalytics.com
Sun Nov 23 18:40:55 CET 2003


On Sun, 2003-11-23 at 11:30, Tord Snall wrote:
> Dear all,
> 
> As part of a larger function, I am randomly removing rows from a data
> frame. The number of removed rows is determmined by a Poisson distribution
> with a low mean. Sometimes, the random number is 0, and that's when the
> problem starts:
> 
> My data frame:
> > temp
>     occ        x        y dbh  age
> 801   0 2977.196 3090.225   6 36.0
> 802   0 2951.892 3083.769   8 40.6
> 803   0 2919.111 3075.557   8 40.6
> 804   0 2914.123 3072.700   9 42.9
> 805   0 2925.353 3074.675   8 40.6
> 
> How many rows (nft) shall be removed?
> > nft<- rpois(1, 2)
> > nft
> [1] 2
> 
> Ok remove 2 rows:
>  
> > temp2<- temp[-sample(nrow(temp), nft), ]
> > temp2
>     occ        x        y dbh  age
> 801   0 2977.196 3090.225   6 36.0
> 803   0 2919.111 3075.557   8 40.6
> 805   0 2925.353 3074.675   8 40.6
> 
> No problem.
> 
>  
> However, sometimes rpois(1, 2) lead to nft=0, and in that case I do not want 
> 
> > temp2<- temp[-sample(nrow(temp), 0), ]
> > temp2
> [1] occ x   y   dbh age
> <0 rows> (or 0-length row.names)
> > 
> 
> Instead I want
> > temp2<- temp
> > temp2
>     occ        x        y dbh  age
> 801   0 2977.196 3090.225   6 36.0
> 802   0 2951.892 3083.769   8 40.6
> 803   0 2919.111 3075.557   8 40.6
> 804   0 2914.123 3072.700   9 42.9
> 805   0 2925.353 3074.675   8 40.6
> 
> 
> Could someone help whith that?
> 
> 
> Thanks in advance!
> 
> 
> Sincerely,
> Tord


Without seeing your entire function, this particular approach may or may
not fit, but how about:

nft <- rpois(1, 2)
ifelse(nft > 0, temp2 <- temp[-sample(nrow(temp), nft), ], 
       temp2 <- temp)

Essentially, this checks the value of the test:

nft > 0

If TRUE, then remove the rows, else copy the entire df.

See ?ifelse for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list