Reputation: 97
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
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