Home > Software engineering >  How can I extract rows using an character in a column?
How can I extract rows using an character in a column?

Time:11-18

I want to extract every next row in column 'Procedure' where the character is equal to p2.

df <- data.frame(
  Sub = c(1:15),
  var = c(400,300,346,432,203,480,760,274,284,592,248,714,384,394,528),
  Procedure = c("p1","p2","p1","p1","p2","p1","p1","p1","p2","p1","p1","p2","p1","p1","p1")
 )

like this

enter image description here

CodePudding user response:

You may use the lag() function here from dplyr:

df_out <- df[lag(df$Procedure == "p2"), ]
df_out

   Sub var Procedure
NA  NA  NA      <NA>
3    3 346        p1
6    6 480        p1
10  10 592        p1
13  13 384        p1

CodePudding user response:

Base R solution:

df[which(df$Procedure == "p2")   1, ]
  •  Tags:  
  • r
  • Related