将字符串分为3列:文本,数字,文本

时间:2017-06-14 15:05:39

标签: r string split

我正在使用大型数据集(大约1500行),当我构建数据集时,我没有提前考虑分离我的标识符,因此他们将它们集中到一个长字符串中。

标识字符串位于标有" Polygon_Name"的列中。我想保留此列,并将此列中的字符串值拆分为3个附加列。

例如,如果有任何" Polygon_Name"单元格中嵌入了一个数字,例如Canker14B,我希望最终得到以下列:(1)原始的Polygon_Name,(2)数字前的所有文本,(3)数字,(4) )数字后的所有文字。

我的数据的小部分:

df <- structure(list(Bolt_ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L), .Label = "N1T.3.4.15.0.C", class = "factor"), 
    Polygon_Name = structure(c(10L, 1L, 9L, 6L, 3L, 7L, 2L, 8L, 
    4L, 5L), .Label = c("C", "Canker15B", "Canker15Left", "Canker15Right", 
    "Canker16", "Canker17", "CankS15B", "CankS16", "CankS17", 
    "S"), class = "factor"), Measure = c(19.342, 25.962, 0.408, 
    0.008, 0.074, 0.41, 0.011, 0.251, 0.056, 0.034)), .Names = c("Bolt_ID", 
"Polygon_Name", "Measure"), row.names = c(1L, 2L, 4L, 5L, 6L, 
7L, 8L, 9L, 10L, 11L), class = "data.frame")

当前输出:

enter image description here

终极输出(我手动构建):

enter image description here

我已经弄清楚如何使用以下代码提取数字:

library(stringr)
regexp <- "[[:digit:]]+"
df$Poly_Num <- str_extract(df$Polygon_Name, regexp)

但是我仍然在努力在数字之前和之后提取文本。任何想法都将不胜感激。

2 个答案:

答案 0 :(得分:3)

tidyverse的想法是,

library(tidyverse)

df %>% 
 mutate(Poly_num = gsub('\\D+', '', Polygon_Name)) %>% 
 separate(Polygon_Name, into = c('Poly_type', 'Poly_letter'), sep = '[0-9]+', remove = FALSE)

#          Bolt_ID  Polygon_Name Poly_type Poly_letter Measure Poly_num
#1  N1T.3.4.15.0.C             S         S        <NA>  19.342         
#2  N1T.3.4.15.0.C             C         C        <NA>  25.962         
#3  N1T.3.4.15.0.C       CankS17     CankS               0.408       17
#4  N1T.3.4.15.0.C      Canker17    Canker               0.008       17
#5  N1T.3.4.15.0.C  Canker15Left    Canker        Left   0.074       15
#6  N1T.3.4.15.0.C      CankS15B     CankS           B   0.410       15
#7  N1T.3.4.15.0.C     Canker15B    Canker           B   0.011       15
#8  N1T.3.4.15.0.C       CankS16     CankS               0.251       16
#9  N1T.3.4.15.0.C Canker15Right    Canker       Right   0.056       15
#10 N1T.3.4.15.0.C      Canker16    Canker               0.034       16

单行将使用extract中的tidyr(@docendodiscimus的赞美)

tidyr::extract(df, Polygon_Name, c("a","b","c"), "^([^0-9]+)(\\d*)([^0-9]*)$", 
                                                       remove = FALSE, convert = TRUE)

答案 1 :(得分:1)

由于您已经在使用stringr,因此可以使用str_match

获取这些内容
str_match(df$Polygon_Name, "([[:alpha:]]*)([[:digit:]]*)([[:alpha:]]*)")[,2:4]
      [,1]     [,2] [,3]   
 [1,] "S"      ""   ""     
 [2,] "C"      ""   ""     
 [3,] "CankS"  "17" ""     
 [4,] "Canker" "17" ""     
 [5,] "Canker" "15" "Left" 
 [6,] "CankS"  "15" "B"    
 [7,] "Canker" "15" "B"    
 [8,] "CankS"  "16" ""     
 [9,] "Canker" "15" "Right"
[10,] "Canker" "16" ""  

要将其添加到现有的data.frame,您可以使用

PName = str_match(df$Polygon_Name, "([[:alpha:]]*)([[:digit:]]*)([[:alpha:]]*)")[,2:4]
df = data.frame(df, PName)
names(df)[4:6] = c("Poly_Type", "Poly_Num", "Poly_Letter")