I am a beginner in R. I have a table having only one column but many rows. I need to extract certain rows between two consecutive blank rows to a single column. Or need to extract rows between two strings at two different rows. I do not know how to do that. Thank you in advance.
Asked
Active
Viewed 51 times
-7
-
6Please include sample data, expected output and the code you have tried. See: [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – markus Aug 29 '18 at 11:59
-
2Don't expect a fully written code when you have not even given time to frame the question well!! Thanks – Rahul Agarwal Aug 29 '18 at 12:08
-
1You are very unprecise with your language. Please clarify: `"table"` you probably mean a `data.frame` or `matrix`. `"blank rows"` do you mean an empty string `""` or a missing value `NA`? `"extract rows between two strings at two different rows"` that's very broad. You tell nothing about the characteristics/form of the string. – Andre Elrico Aug 29 '18 at 12:37
-
In any case. Your question can be solved with `regular expressions` and `?grepl`. – Andre Elrico Aug 29 '18 at 12:39
1 Answers
1
Welcome to Stack Exchange and thanks for your post. However I recommend to read Minimal reproducible & verifiable example and How to ask post. You will increase probability to get an answer significantly.
To subset column in between two strings between you can use the following approach (gsub
and data.frame
subsetting):
df <- data.frame(foo = c("X","", "A", "B", "C", "D", "A", "", "E"), stringsAsFactors = FALSE)
df
# foo
# 1 X
# 2
# 3 A
# 4 B
# 5 C
# 6 D
# 7 A
# 8
# 9 E
# empty string
empty_between <- grep("^$", df$foo)
df[(empty_between[1] + 1):(empty_between[2] - 1), , drop = FALSE]
# foo
# 3 A
# 4 B
# 5 C
# 6 D
# 7 A
# between two strings (in this case "A")
string_between <- grep("^A$", df$foo)
df[(string_between[1] + 1):(string_between[2] - 1), , drop = FALSE]
# foo
# 4 B
# 5 C
# 6 D

Artem
- 3,304
- 3
- 18
- 41