简体   繁体   English

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

[英]split data.frame by varying value in first column

Similar to Split data.frame by value I want to split a df by value.类似于Split data.frame by value我想按值拆分 df 。 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)

I want to split by a*.我想除以*。 It should look like this:它应该如下所示:

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

I tried this to get it我试过这个来得到它

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?但是我怎么说 R,不同的值出现在 a 之后?

You can use grepl to match a pattern and cumsum over it to create groups.您可以使用grepl匹配模式并在其上进行cumsum以创建组。

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 : tidyverse中的等效答案:

library(dplyr)
library(stringr)

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

We can also do this with我们也可以这样做

split(df, cumsum(startsWith(as.character(df$var1), "a")))
#$`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

Or with substr或者用substr

split(df, cumsum(substr(df$var1, 1, 1) == 'a'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM