the_witch_dr
the_witch_dr

Reputation: 123

Subset rows based on "start and stop" strings

looking to write an R script that will search a column for a specific value and begin sub setting rows until a specific text value is reached.

Example:

    X1  X2 
[1,] "a" "1"
[2,] "b" "2"
[3,] "c" "3"
[4,] "d" "4"
[5,] "e" "5"
[6,] "f" "6"
[7,] "c" "7"
[8,] "k" "8"

What I'd like to do is search through X1 until the letter 'c' is found, and begin to subset rows until another letter 'c' is found, at which point the subset procedure would stop. Using the above example, the result should be a vector containing c(3,4,5,6,7).

Assume there will be no more than 2 rows where X1 equals 'c'

Any help is greatly appreciated.

Upvotes: 1

Views: 364

Answers (1)

Emil Bode
Emil Bode

Reputation: 1840

You can lookup where a value is with the function which, and use that as in index to get the values you are looking for. If you want everything from the first to the second "c", it would look like this:

indices <- which(df$X1=='c')
range <- indices[1]:indices[2]
df$X2[range]

Upvotes: 4

Related Questions