2017-10-05 55 views
1

我有一個data.frame,列中有「進攻」。每次進攻由文章(藝術),一個段落(ABS)和第(齊夫)的:通過分隔符將列分成多列

df<-data.frame(offence=c("Art. 110 Abs. 3 StGB","Art. 10 Abs. 1 StGB", "Art. 122 SVG", "Art. 1 Ziff. 2 UWG")) 

> df 
       offence 
1 Art. 110 Abs. 3 StGB 
2 Art. 10 Abs. 1 StGB 
3   Art. 122 SVG 
4 Art. 1 Ziff. 2 UWG 

但我需要把它以這樣的形式:

Art Ziff Abs Law 
1 110 NA 3 StGB 
2 10 NA 1 StGB 
3 122 NA NA SVG 
4 1 2 NA UWG 

是什麼獲得這個結果的最好方法是什麼? lapply?

謝謝!

回答

1

可以使用str_extractstringr

library(stringr) 
library(dplyr) 

df$offence %>% 
    {data.frame(Art = str_extract(., "(?<=Art[.]\\s)\\d+"), 
       Ziff = str_extract(., "(?<=Ziff[.]\\s)\\d+"), 
       Abs = str_extract(., "(?<=Abs[.]\\s)\\d+"), 
       Law = str_extract(., "\\w+$"))} 

結果:

Art Ziff Abs Law 
1 110 <NA> 3 StGB 
2 10 <NA> 1 StGB 
3 122 <NA> <NA> SVG 
4 1 2 <NA> UWG 
+0

大,非常感謝你! –

1

將其轉換爲DCF形式(即關鍵字:值),使用gsub,然後在使用read.dcf讀取它。最後將read.dcf生成的矩陣轉換爲數據框並將任意數量的列轉換爲數字。沒有包被使用。

s <- gsub("(\\S+)[.] (\\d+)", "\\1: \\2\n", df[[1]]) # convert to keyword: value 
s <- sub(" (\\D+)$", "Law: \\1\n\n", s) # handle Law column 
us <- trimws(unlist(strsplit(s, "\n"))) # split into separate components 
DF <- as.data.frame(read.dcf(textConnection(us)), stringsAsFactors = FALSE) 
DF[] <- lapply(DF, type.convert) 

捐贈:

Art Abs Law Ziff 
1 110 3 StGB NA 
2 10 1 StGB NA 
3 122 NA SVG NA 
4 1 NA UWG 2