2017-06-14 46 views
3

我正在處理一個大型數據集(約1500行),並且當我構建數據集時,我沒有想到提前分離我的標識符,所以它們是集中成一個長串。將字符串分成3列:文本,數字,文本

標識字符串位於標有「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

最終輸出(I這個手動建立):

enter image description here

我已經想出瞭如何提取用下面的代碼數量:

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

但我仍然在努力前後數後拉出來的文字。任何想法將不勝感激。

回答

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 

一個班輪將是既然你已經使用stringr使用extracttidyr(@docendodiscimus致意)

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

,你可以得到這些使用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" "" 

要將此添加到您現有的數據幀中,您可以使用

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") 
+0

非常乾淨,短的選項。我也喜歡這個解決方案不會在任何列中放置「NA」。 – KKL234