通过改变第一列中的值来分割data.frame

Similar to Split data.frame by value I want to split a df by value. In my case the value is not always exactly the same. I tried this but did not succed:

df <- data.frame(var1 = c("ab", 1, 2, 3, "ac", 1, 2, 3, 4, 5, 6, "ad", 1, 2), var2 = 1:14)

我想除以*。它看起来应该像这样:

ab 1
1 2
2 3
3 4

ac 5
1 6
2 7
3 8
4 9
5 10
6 11

ad 12
1 13
2 14

我试图这样做

df[,1] == "a*"
#it shows all over 0

#I would do sth. like that
#split(df, cumsum(df[,1] == "a*"))

I think the * is wrong. But how do I say R, that varying values come after a?

评论
没人疼?
没人疼?

You can use grepl to match a pattern and cumsum over it to create groups.

split(df, cumsum(grepl('a.*', df$var1)))


#$`1`
#  var1 var2
#1   ab    1
#2    1    2
#3    2    3
#4    3    4

#$`2`
#   var1 var2
#5    ac    5
#6     1    6
#7     2    7
#8     3    8
#9     4    9
#10    5   10
#11    6   11

#$`3`
#   var1 var2
#12   ad   12
#13    1   13
#14    2   14

An equivalent answer in tidyverse :

library(dplyr)
library(stringr)

df %>%  group_split(cumsum(str_detect(var1, 'a.*')), keep = FALSE)
点赞
评论