【问题标题】:Split elements in vector to different column with fread使用 fread 将向量中的元素拆分到不同的列
【发布时间】:2019-05-04 20:37:54
【问题描述】:

假设我有超过 20M 行的非常大的 TSV 文件,如下所示:

    a b {"condition1":["ABC"], "condition3":false, "condition4":4000}
    c c {"condition1":["BBB"],"condition2":true}

我需要它看起来像:

     Var1 Var2 Condition1 Condition2 Condition3 Condition4
     a    b    ABC        NA         FALSE      4000
     c    c    BBB        TRUE       NA         NA

我尝试了以下代码,但它是: 一种。效率低下 湾。不工作

在阅读时分离第三列的现成解决方案?

     dt<-fread(input = ifilename, header = T,encoding = "UTF-8" )
     output<-dt[,c("filter")]  #assume the third column named "filter"
     fwrite(x = output,file = "./DB/filter.csv",)
     filter.db<-fread(input ="./DB/filter.csv",fill=T)

【问题讨论】:

  • 你确定你有TRUE而不是trueTrue吗?这些数据看起来很像 JSON 或 python 字典,并且有许多工具可以解析这些对象(例如 jsonlite 包)。
  • 你说得对,我编辑了。
  • 一次一件事! 1.读取数据。 2. 列拆分/json 解析 3. 添加回data.frame

标签: r data.table fread


【解决方案1】:

一个可能的解决方案:

library(data.table)
library(jsonlite)

to_add <- rbindlist(lapply(dt$V3, function(x) setDT(fromJSON(x))), fill = TRUE)
setcolorder(to_add, sort(names(to_add)))

dt[, names(to_add) := to_add][, V3 := NULL][]

给出:

   V1 V2 condition1 condition2 condition3 condition4
1:  a  b        ABC         NA      FALSE       4000
2:  c  c        BBB       TRUE         NA         NA

使用过的数据:

dt <- structure(list(V1 = c("a", "c"),
                     V2 = c("b", "c"),
                     V3 = c("{\"condition1\":[\"ABC\"], \"condition3\":false, \"condition4\":4000}",
                            "{\"condition1\":[\"BBB\"],\"condition2\":true}")),
                .Names = c("V1", "V2", "V3"), row.names = c(NA, -2L), class = c("data.table", "data.frame"))

【讨论】:

  • 感谢所有建议。但是,就时间而言,在我加载它们之后稀疏 23M 行似乎是相当昂贵的。有什么想法吗?
【解决方案2】:

*nix 工具在这种情况下可能会更快,因为 R 中的 json 解析器在我的测试中有点慢。

> library(data.table)
> aTbl = fread(cmd="cat foo.txt | grep -P -o '^\\w+\\s+\\w+'", header=F)
> aTbl
   V1 V2
1:  a  b
2:  c  c

> bTbl = fread(cmd="cat foo.txt | grep -P -o '[{].*$' | jq -r '[ .condition1[], .condition2, .condition3, .condition4 ] | @csv'", header=F)
> bTbl
    V1   V2    V3   V4
1: ABC   NA FALSE 4000
2: BBB TRUE    NA   NA

> setnames(aTbl, c('Var1', 'Var2'))
> setnames(bTbl, c('Condition1', 'Condition2', 'Condition3', 'Condition4'))

> cTbl = cbind(aTbl, bTbl)
> cTbl
   Var1 Var2 Condition1 Condition2 Condition3 Condition4
1:    a    b        ABC         NA      FALSE       4000
2:    c    c        BBB       TRUE         NA         NA
>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2018-07-18
    相关资源
    最近更新 更多