【问题标题】:Read csv file into R that contains brackets at at the start and end of each line将csv文件读入R中,每行的开头和结尾都包含括号
【发布时间】:2014-07-07 14:18:23
【问题描述】:

我有一个如下所示的文本文件

(abc,123)
(def,456)
(ghi,789)
...

在 R 中,我想将此文件读取为 csv。因此,我需要去掉行尾的左括号和右括号。您知道如何实现这一目标吗?

如果可能,应避免读取文件、删除括号和写入临时文件。

【问题讨论】:

  • 为什么需要这些限制?
  • 如果我继续修修补补,我敢打赌我可以使用pipe 和 unix 命令tr 得到一些有用的东西,并将结果直接发送到read.csv。有比我更好的外壳方面的人可能能够更快地将碎片拼凑在一起。
  • ...修补成功,请看下面我的回答。

标签: r csv


【解决方案1】:

好的,这似乎可行(在我的 Mac 上):

read.table(pipe("tr -d '()' < ~/Desktop/paren.txt"),header = FALSE,sep = ",")
   V1  V2
1 123 abc
2 456 def
3 789 ghi

【讨论】:

  • 您有 Mac?您是数据科学家吗?
  • @DavidArenburg 不,我不可能成为一名数据科学家。我太擅长统计,太不擅长编程,无法获得资格。
【解决方案2】:

疯狂的想法时间,但您可以创建自己的 colClasses 定义并在 read.table 中使用它们,如下所示:

setClass("strippedL")
setClass("strippedR")
setAs("character", "strippedL",
      function(from)  as.character( gsub("(", "", from, fixed=TRUE)))
setAs("character", "strippedR",
      function(from)  as.numeric( gsub(")", "", from, fixed=TRUE)))

这是它的使用方法。将 text 参数替换为 file 参数以访问文件。

read.table(text = "(abc,123)
                   (def,456)
                   (ghi,789)", 
           sep = ",", header = FALSE, 
           colClasses = c("strippedL", "strippedR"))
#    V1  V2
# 1 abc 123
# 2 def 456
# 3 ghi 789

不那么疯狂(但更慢)的想法:从“gsubfn”的开发版本中尝试read.pattern

library(gsubfn)
source("http://gsubfn.googlecode.com/svn/trunk/R/read.pattern.R")

pat <- "^\\((.*),(.*)\\)$"
read.pattern("~/path/to/file.txt", pattern=pat, header = FALSE)

【讨论】:

  • 看我的时间测试——我很高兴没有在实际函数中包含类定义:-)
【解决方案3】:

我可能会走readLines 路线,因为需要先操作文件。然后你仍然可以在read.csv/table 中使用text 参数

> writeLines(c("(abc,123)", "(def,456)", "(ghi,789)"), "yourfile.txt") 
   ## put your data in a file
> txt <- gsub("[()]", "", readLines("yourfile.txt"))
> read.csv(text = txt, header = FALSE)
#    V1  V2
# 1 abc 123
# 2 def 456
# 3 ghi 789

> read.table(text = txt, sep = ",")
#    V1  V2
# 1 abc 123
# 2 def 456
# 3 ghi 789

【讨论】:

    【解决方案4】:

    你可以试试:

     str1 <- c("(abc,123)","(def,456)","(ghi,789)")
     library(qdap)
     read.table(text=unlist(bracketXtract(str1, "round")),sep=",")
     #  V1  V2
     #1 abc 123
     #2 def 456
     #3 ghi 789
    

    【讨论】:

      【解决方案5】:

      坦率地说,处理这种情况的最佳方法是在将源文件读入R 之前对其进行编辑。我可以想象没有理由避免这种情况,需要编写一些花哨的R 代码来删除读取数据后的括号。

      打开您选择的文本编辑器并告诉它(编辑器)删除所有括号。保存文件(必要时保存到新文件),然后使用 read.csv 打开新文件。

      但如果必须的话,

      foo<- read.csv(your_file)
      gsub('(','',foo)
      gsub(')','',foo)
      foo[,2]<-as.numeric(foo[,2])
      

      编辑:运行速度测试:

      paren1<-function(file) {
          foo<- read.csv(file)
      gsub('[()]','',foo)
      #gsub(')','',foo)
      foo[,2]<-as.numeric(foo[,2])
      }
      
      setClass("strippedL")
      setClass("strippedR")
      setAs("character", "strippedL",
            function(from)  as.character( gsub("(", "", from, fixed=TRUE)))
      setAs("character", "strippedR",
            function(from)  as.numeric( gsub(")", "", from, fixed=TRUE)))
      paren2<-function(file) {
            foo<- read.table(file,sep = ",", header = FALSE, colClasses = c("strippedL", "strippedR"))
            return(invisible(foo))
      }
      
      library(microbenchmark)
      # my "paren.txt" has 860 lines in it
      microbenchmark(paren1('paren.txt'),paren2('paren.txt'))
      
      Unit: milliseconds
                      expr      min       lq   median       uq      max neval
       paren1("paren.txt") 3.341024 3.461614 3.486416 3.514639 4.060715   100
       paren2("paren.txt") 2.164631 2.251439 2.285007 2.322211 5.681836   100
      

      因此,Ananda 的解决方案明显更快。哦,好吧:-)

      【讨论】:

      • 这不会把 gsub("[()]","",foo) 作为一行来工作吗?
      【解决方案6】:

      这是一个使用gsub 函数的选项,用于data.frame 的第一列和第二列:

      tmp <- read.table("tmp.csv", sep=",", stringsAsFactors=FALSE)
      
      #tmp <- structure(list(V1 = c("(abc", "(def", "(ghi"), V2 = c("123)", 
      "456)", "789)")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, 
      -3L)) # to reproduce tmp
      
      tmp
      tmp[,1] <- gsub("(", "", tmp[,1], fixed = TRUE)
      tmp[,2] <- gsub(")", "", tmp[,2], fixed = TRUE)
      tmp
      

      【讨论】:

        猜你喜欢
        • 2012-03-26
        • 2017-05-28
        • 1970-01-01
        • 2018-07-11
        • 1970-01-01
        • 2018-05-15
        • 2011-12-17
        • 2019-11-24
        • 1970-01-01
        相关资源
        最近更新 更多