Search code examples
rselectsubsetframedata-manipulation

Manipulate data table with R


I have a data frame, for instance:

X Y

1 -0.1

2 0

3 -0.2

4 -0.4

5 0

6 -0.2

I need R to select all rows between the first and 2nd zero, so that the final table is:

2 0

3 -0.2

4 -0.4

5 0

It does not work with subset. Has anyone an idea to solve this issue?

Thanks in advance!


Solution

  • Use which to get the index position where Y = 0 and subset the data.

    inds <- which(df$Y == 0)
    df <- df[inds[1]:inds[2], ]
    df
    #  X    Y
    #2 2  0.0
    #3 3 -0.2
    #4 4 -0.4
    #5 5  0.0
    

    data

    df <- structure(list(X = 1:6, Y = c(-0.1, 0, -0.2, -0.4, 0, -0.2)), 
          class = "data.frame", row.names = c(NA, -6L))