【问题标题】:R Paste multipleR粘贴多个
【发布时间】:2013-08-07 23:35:55
【问题描述】:

我目前在我的 R 脚本中接收多个命令行参数,例如:

args<-commandArgs(TRUE)
arg1 <- as.numeric(args[1])
arg2 <- as.numeric(args[2])

我想在我的粘贴字符串中使用这些参数,如下所示。我的问题是我只能弄清楚如何使用其中一个参数,而不是两者(arg1,arg2)。我如何使用“arg1”命令行参数代替“xxx”,而不是我在下面的 where 子句中显示的“xxx”(即“columnname1 in (xxx)”)?我尝试了许多不同的方法,但由于某种原因我无法弄清楚。我应该连接两个不同的字符串来完成这个还是有更简单的方法?

SQL<-paste(
"SELECT 
 *
FROM
 table
WHERE
 columnname1 in (xxx)
 and
 columnname2 in ('",arg2,"')",sep = "")

感谢您的帮助!

【问题讨论】:

    标签: r command-line-arguments paste


    【解决方案1】:

    试试:

    SQL<-paste(
    "SELECT 
     *
    FROM
     table
    WHERE
     columnname1 in ('",arg1,"')
     and
     columnname2 in ('",arg2,"')",sep = "", collapse="")
    

    【讨论】:

    • 太棒了!这很好用。我不敢相信那是多么容易。谢谢!
    【解决方案2】:

    您还可以使用以下允许命名替换的辅助函数:

    SQL<-strsubst(
      "SELECT * FROM table WHERE 
       columnname1 in ('$(arg1)') and 
       columnname2 in ('$(arg2)')", 
      list(arg1=arg1, arg2=arg2)
    )
    

    其中strsubst定义如下:

    strsubst <- function (template, map, verbose = getOption("verbose")) 
    {
        pat <- "\\$\\([^\\)]+\\)"
        res <- template
        map <- unlist(map)
        m <- gregexpr(pat, template)
        idx <- which(sapply(m, function(x) x[[1]] != -1))
        for (i in idx) {
            line <- template[[i]]
            if (verbose) 
                cat("input: |", template[[i]], "|\n")
            starts <- m[[i]]
            ml <- attr(m[[i]], "match.length")
            sym <- substring(line, starts + 2, starts + ml - 2)
            if (verbose) 
                cat("sym: |", sym, "|\n")
            repl <- map[sym]
            idx1 <- is.na(repl)
            if (sum(idx1) > 0) {
                warning("Don't know how to replace '", paste(sym[idx1], 
                    collapse = "', '"), "'.")
                repl[idx1] <- paste("$(", sym[idx1], ")", sep = "")
            }
            norepl <- substring(line, c(1, starts + ml), c(starts - 
                1, nchar(line)))
            res[[i]] <- paste(norepl, c(repl, ""), sep = "", collapse = "")
            if (verbose) 
                cat("output: |", res[[i]], "|\n")
        }
        return(res)
    }
    

    【讨论】:

    • 感谢您的建议。我想坚持使用上面提供的粘贴解决方案,但我以后会记住这一点。很有用!
    猜你喜欢
    • 1970-01-01
    • 2019-03-17
    • 2023-01-10
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2013-08-30
    • 2020-02-26
    • 1970-01-01
    相关资源
    最近更新 更多