[R] Delete Block of Rows

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Sun Jun 15 17:36:53 CEST 2008

nmarti wrote:
> I am trying to delete a section of rows from a data frame (based on no
> condition).  Lets say my data frame has 200 rows and I want to delete rows 1
> through 25.  How would I do this?
> I know x[ -1, ] deletes the first row (or any desired row).  I tried using
> different variations of this, like x[ -c(1:25), ] but that didn't work.  
what do you mean by 'didnt work'?
when you use negative indices, rows (or columns) from the input are
skipped in the output.  but to have a side effect of actually changing
the data frame, you need an assignment.  to modify your data frame, you

x = x[-c(<your spec>),]

while x[-c(<your spec>),] will (should) return a df with rows skipped,
but x won't be changed.

> I
> also tried writting a few functions, for example:
> deleteRows <- function( data, s, e, ) {
> for( i in s:e )
> data[ -i, ]
> }
> deleteRows( ds, 1, 25 )
> But that didn't work either, it only deleted row 25 
it didn't work, it didn't even delete row 25 from ds -- it *returned* a
df with all rows of ds except row 25 (in a bad style, i'd say).

> (i'm new to writing
> functions).
consider reading the docs.

note that an implementation like

deleteRows = function(df, s, e) (df = df[-(s:e),,drop=FALSE])

won't work, because in r data frames are passed as arguments to
functions by value (you are welcome to argue that this is insane).


More information about the R-help mailing list