通过分隔符将列拆分为多个列

时间:2017-10-05 14:40:08

标签: r split tidyr strsplit

我有一个带有“冒号”列的data.frame。每一项罪行都包括一篇文章(Art),一段(Abs)和一段(Ziff):

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?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用str_extract中的stringr

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

答案 1 :(得分:1)

使用gsub将其转换为dcf格式(即关键字:值),然后使用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