首页 > 解决方案 > 拆分数据框列——使用第二个大写字母作为分隔符

问题描述

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

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

并且标签在数据框/小标题中

myTibble <- tibble(Label = Label)
myTibble

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

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

标签: rregexstringr

解决方案


你也可以separate从 tidyr使用

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

推荐阅读