【问题标题】:grep or pmatch?grep 还是 pmatch?
【发布时间】:2011-10-16 20:08:33
【问题描述】:

我正在尝试从目录中导入一系列文件并将它们中的每一个转换为一个数据框。我还想使用文件标题创建两个具有标题相关值的新列。输入文件的格式为:xx_yy.out 其中 XX 当前可以是三个值之一。 YY 当前有两个可能的值。未来这些数字还会上升。


基于 cmets 编辑解决方案(原始问题见下文)


再次编辑以反映@JoshO'Brien 的建议

filelist <- as.list(dir(pattern = ".*.out"))

for(i in filelist) {

    tempdata  <- read.table(i)                  #read the table
    filelistshort <- gsub(".out$", "", i)       #remove the end of the file
    tempsplit <- strsplit(filelistshort, "_")   #remove the underscore
    xx <- sapply(tempsplit, "[", 1)             #get xx
    yy <- sapply(tempsplit, "[", 2)             #get yy
    tempdata$XX <- xx                           #add XX column
    tempdata$YY <- yy                           #add YY column
    assign(gsub(".out","",i), tempdata)         # give the dataframe a shortened name

}

下面是原始代码,显示我想使用一些方法来获取 XX 和 YY 值,但不确定最好的方法:

我的大纲(在@romanlustrik post 之后)如下:

filelist <- as.list(dir(pattern = ".*.out"))
lapply(filelist, FUN = function(x) {
    xx <- grep() or pmatch()
    yy <- grep() or pmatch()
    x <- data.frame(read.table(x)) 
    x$colx <- xx
    x$coly <- yy
    return(x)
})

其中xx &lt;-yy &lt;- 行将是基于pmatch 或grep 的查找。我正在玩弄其中一项工作,但欢迎任何建议。

【问题讨论】:

    标签: r lookup


    【解决方案1】:

    如果我们可以假设您的文件名将只包含一个"_",我根本不会使用grep()pmatch()

    strsplit() 似乎提供了一个更干净更简单的解决方案:

    filelist <- c("aa_mm.out", "bb_mm.out", "cc_nn.out")
    
    # Remove the trailing ".out"
    rootNames <- gsub(".out$", "", filelist)
    
    # Split string at the "_"
    rootParts <- strsplit(rootNames, "_")
    
    # Extract the first and second parts into character vectors
    xx <- sapply(rootParts, "[", 1)
    yy <- sapply(rootParts, "[", 2)
    
    xx
    # [1] "aa" "bb" "cc"
    yy
    # [1] "mm" "mm" "nn"
    

    【讨论】:

    • @zach -- 没问题。为了紧凑性和可靠性,您可能希望将所有计算放入单个 for() 循环或调用 lapply()。如果您使用lapply() 路线,则需要通过指定assign("objectName", object, envir=.GlobalEnv) 来确保分配发生在全局环境中。
    【解决方案2】:

    这是一个丑陋的 hack,但可以完成工作。

    fl <- c("12_34.out", "ab_23.out", "02_rk.out")
    xx <- regexpr(pattern = ".._", text = fl)
    XX <- (substr(fl, start = xx, stop = xx + attr(xx, "match.length")-1))
      [1] "12" "ab" "02"
    yy <- regexpr(pattern = "_..", text = fl)
    YY <- (substr(fl, start = yy + 1, stop = yy + attr(yy, "match.length")-1))
      [1] "34" "23" "rk"
    

    【讨论】:

      猜你喜欢
      • 2014-04-29
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-21
      • 2011-12-03
      • 1970-01-01
      相关资源
      最近更新 更多