[R] remove 0 rows from a data frame

Tord Snall tord.snall at ebc.uu.se
Sun Nov 23 18:30:27 CET 2003


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



-----------------------------------------------------------------------
Tord Snäll
Avd. f växtekologi, Evolutionsbiologiskt centrum, Uppsala universitet
Dept. of Plant Ecology, Evolutionary Biology Centre, Uppsala University
Villavägen 14			
SE-752 36 Uppsala, Sweden
Tel: 018-471 28 82 (int +46 18 471 28 82) (work)
Tel: 018-25 71 33 (int +46 18 25 71 33) (home)
Fax: 018-55 34 19 (int +46 18 55 34 19) (work)
E-mail: Tord.Snall at ebc.uu.se
Check this: http://www.vaxtbio.uu.se/resfold/snall.htm!




More information about the R-help mailing list