【问题标题】:splitting a data frame column -- using the second capital letter as a delimiter拆分数据框列——使用第二个大写字母作为分隔符
【发布时间】:2020-11-11 01:19:47
【问题描述】:

我有一个这样的标签列表。

Label = c("ProjectCrash", "ProjectNoCrash", "TreatmentFed", "TreatmentPre", 
"TreatmentStarve")

标签位于数据框/小标题中

myTibble <- tibble(Label = Label)
myTibble

我想再创建两列,用第二个大写字母分隔。 所以第一列将包含“项目”或“治疗”。

第二个将包含 Crash、NoCrash、Fed、Pre 或 Starve 之一。

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    您可以通过提供正则表达式来使用tidyr 的extract 将数据提取到不同的列中。

    tidyr::extract(myTibble, Label, c('First', 'Second'), 
                  '([A-Z][a-z]+)([A-Z].*)', remove= FALSE)
    
    # A tibble: 5 x 3
    #  Label           First     Second 
    #  <chr>           <chr>     <chr>  
    #1 ProjectCrash    Project   Crash  
    #2 ProjectNoCrash  Project   NoCrash
    #3 TreatmentFed    Treatment Fed    
    #4 TreatmentPre    Treatment Pre    
    #5 TreatmentStarve Treatment Starve 
    

    【讨论】:

    • 这很好用。所以我认为这种情况下的正则表达式分为两组。第一个,由第一组括号表示,是一个大写字母,后跟一些小写字母。第二个是大写字母,后跟所有其余字母,不分大小写。
    • 没错。对于您的示例,使用与第一组相同的正则表达式也可以使用([A-Z][a-z]+)([A-Z][a-z]+)。
    【解决方案2】:

    你也可以使用来自 tidyr 的separate

    tidyr::separate(myTibble, Label,c("a","b"), "(?<=[a-z])(?=[A-Z])", 
                    extra = "merge", remove = FALSE)
    # A tibble: 5 x 3
      Label           a         b      
      <chr>           <chr>     <chr>  
    1 ProjectCrash    Project   Crash  
    2 ProjectNoCrash  Project   NoCrash
    3 TreatmentFed    Treatment Fed    
    4 TreatmentPre    Treatment Pre    
    5 TreatmentStarve Treatment Starve 
    

    在基础 R 中,您可以这样做:

    transform(myTibble, a=strcapture('([A-Z][a-z]+)(\\w+)',Label, 
                      data.frame(a=character(), b=character())))
                Label       a.a     a.b
    1    ProjectCrash   Project   Crash
    2  ProjectNoCrash   Project NoCrash
    3    TreatmentFed Treatment     Fed
    4    TreatmentPre Treatment     Pre
    5 TreatmentStarve Treatment  Starve
    

    【讨论】:

    • 这也有效。谢谢!也就是说,从概念上讲,我在遵循正则表达式所做的事情时遇到了更多麻烦。我能得到提示吗?
    猜你喜欢
    • 2021-05-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多