I am having a simple problem in R. I am working with a big dataset where I am trying to select any row that matches a certain criteria, along with the two rows above it and two rows below it in a dataframe. Here's what my data looks like
df <- structure(c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21",
"22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
"33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43",
"44", "45", "46", "47", "48", "49", "50", "a", "b", "a", "a",
"a", "b", "a", "a", "a", "b", "a", "a", "a", "a", "a", "a", "a",
"a", "a", "b"), .Dim = c(10L, 7L), .Dimnames = list(NULL, c("1",
"2", "3", "4", "5", "6", "7")))
I am looking for instances with "b" in column6 and "a" in column7. selecting those instances can be done via this command:
rows <- df[which(df[,6] == "b"& df[,7] =="a"),]
But I am not sure how I can select two higher and two lower instances (esp that the first hit that matches the criteria has one higher instance). This is supposed to be basic but I couldn't figure out a good way to do it. Any ideas?
Thanks