Bjorn
Bjorn

Reputation: 97

Subsetting column and select next n rows based on value in the same column

I have a column in a data frame that I would like to subset based on a header in the same column. It essentially looks something like this:

df <- data.frame(col = c("Var: A", "1", "3", "5", "Var:B", "2", "4", "6", "7", "Var: C", "7", "1"))

[df]
      col
1  Var: A
2       1
3       3
4       5
5   Var:B
6       2
7       4
8       6
9       7
10 Var: C
11      7
12      1

What I want to do is to subset this column based on the different 'Var' headings, to end up with this:

[1] Var: A
         1
         3
         5
[2] Var: B
         2
         4
         6
         7

And finally to store them in different variables.

I have looked at examples explaining how to select n rows before or after a specific value in a column, but unfortunately most of the variables I want to extract are of different length so that won't work. Is there any way this can be done in a relatively straightforward way?

Upvotes: 1

Views: 93

Answers (1)

Sotos
Sotos

Reputation: 51582

You can use grepl to find the Vars and split, i.e.

split(df, cumsum(grepl('Var', df$col)))

which gives,

$`1`
     col
1 Var: A
2      1
3      3
4      5

$`2`
    col
5 Var:B
6     2
7     4
8     6
9     7

$`3`
      col
10 Var: C
11      7
12      1

Upvotes: 2

Related Questions