【问题标题】:Split a string into multiple columns of variable length using R使用R将字符串拆分为多个可变长度的列
【发布时间】:2017-05-05 15:28:19
【问题描述】:

我正在寻找一种更快的方法来完成以下操作,我需要将包含字符串的 data.table 对象的列拆分为单独的列。字符串的格式为“name1=value1;name2=value2;”。字符串可以拆分为可变数量的列,在这种情况下,这些值需要用 NA 填充。例如我有这个:

library(data.table)
dt <- data.table("foo"=c("name=john;id=1234;last=smith", "name=greg;id=5678", "last=picard", "last=jones;number=1234567890"))

我想要这个:

name id last number john 1234 smith NA greg 5678 NA NA NA NA picard NA NA NA jones 1234567890

这可行,但考虑到要解析的数据量,它很慢,我想知道是否有更好的方法:

x <- strsplit(as.character(dt$foo), ";|=")
a <- function(x){
     name <- x[seq(1, length(x), 2)]
     value <- x[seq(2, length(x), 2)]
     tmp <- transpose(as.data.table(value))
     names(tmp) <- name
     return(tmp)
  }
x <- lapply(x, a)
x <- rbindlist(x, fill=TRUE)

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    我们可以试试:

    # split into different fields for each row
    res <- lapply(strsplit(dt$foo, ';'), function(x){
        # split the the fields into two vectors of field names and field values
        res <- tstrsplit(x, '=')
        # make a list of field values with the field names as names of the list 
        setNames(as.list(res[[2]]), res[[1]])
    })
    
    rbindlist(res, fill = T)
    #    name   id   last     number
    # 1: john 1234  smith         NA
    # 2: greg 5678     NA         NA
    # 3:   NA   NA picard         NA
    # 4:   NA   NA  jones 1234567890
    
    dplyr::bind_rows(res)
    
    # # A tibble: 4 × 4
    #    name    id   last     number
    #   <chr> <chr>  <chr>      <chr>
    # 1  john  1234  smith       <NA>
    # 2  greg  5678   <NA>       <NA>
    # 3  <NA>  <NA> picard       <NA>
    # 4  <NA>  <NA>  jones 1234567890
    

    根据 David Arenburg 的评论,我们可以通过将 fixed = TRUE 添加到 strsplit 来提高速度。我用这个数据做了一个简短的基准测试,添加fixed = TRUE 将使速度提高大约一倍。

    library(microbenchmark)
    
    dt <- dt[sample.int(nrow(dt), 100, replace = T)]
    
    microbenchmark(
        noFix = {
            res <- lapply(strsplit(dt$foo, ';'), function(x){
                res <- tstrsplit(x, '=')
                setNames(as.list(res[[2]]), res[[1]])
            })
        },
        Fixed = {
            res <- lapply(strsplit(dt$foo, ';', fixed = TRUE), function(x){
                res <- tstrsplit(x, '=', fixed = TRUE)
                setNames(as.list(res[[2]]), res[[1]])
            })
        },
        times = 1000
    )
    # Unit: milliseconds
    #  expr      min       lq     mean   median       uq       max neval
    # noFix 1.921947 1.999386 2.212511 2.064997 2.218706 11.290072  1000
    # Fixed 1.026753 1.088712 1.226519 1.131899 1.219558  4.490796  1000
    

    【讨论】:

    • Prolly 希望 type.convert=TRUE 在 tstrsplit 中,这样 `number 是 num 而不是 char。
    • @Frank,我认为这不起作用,因为在tstrsplit 之后,数字将与名称在同一个向量中,因此它将被强制转换为字符。如果需要,我们可以在rbindlist 之后转换为数字。
    • 它确实记录在grep 等之下。它只是进行精确匹配,而不是运行便宜得多的正则表达式引擎。使用grep等基本函数,速度差异甚至可以达到10倍。根据经验,每当您进行完全匹配而不是某个表达式时,请始终添加fixed = TRUE- 输入更多,但通常会得到回报。
    • @DavidArenburg,速度确实提高了 10 倍左右。我玩了这个例子,发现fixed=T 对单个字符效果很好,如果使用更长的固定模式,改进会减少到大约 4 倍。
    • 是的,这取决于用例,但它肯定不会表现得更差。如果您的分隔符是元字符而您忘记了,它实际上也更安全。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多