使用R中的函数检查对象和文件是否存在

时间:2015-04-07 11:48:21

标签: r

我有一个脚本接受这种形式的一些参数: Rscript script.R -o=output -x=density.xvg -t=temperature.xvg -u=potential.xvg -p=pressuree.xvg -...

所有文件都是.xvg(文本文件),并按列结构化。

#    title "Secondary Structure"
#    xaxis  label "Time (ns)"
#    yaxis  label "Number of Residues"
#TYPE xy
   0   637   180   201     7    94   129   300     0    47     1
   1   617   189   191    11    99   121   294     5    48     1
   2   625   183   198     7    97   130   290     0    53     1
   3   625   180   195     5   102   125   300     0    51     1

我从bash脚本调用R脚本,该脚本设置所有可能的标志,即使某些文件不存在。 R脚本应检查文件和变量是否存在并执行特定功能(绘图温度曲线,绘图密度,...)。 脚本首先检查是否设置了标志并将其值(文件名)分配给变量(对于-u=potential.xvg我得到file.potential <- "potential.xvg")。

然后,脚本使用

检查变量和文件是否存在
if (!exists("file.potential")) {
  cat('the variable "',file.potential,'" is not set\n')
} else {
  if (file.exists(paste(file.potential))) {
    cat("ok\n")
  } else {
    cat('the file "',paste(file.potential),'" does not exist\n')
  } 
}

因为我有几个标志,我写了一个函数:

checkExistance <- function(a) {
  if (!exists("a")) {
    cat('the variable "',a,'" is not set\n')
  } else {
    if (file.exists(paste(a))) {
      cat("ok\n")
    } else {
      cat('the file "',paste(a),'" does not exist\n')
    } 
  }
}

正确检查变量的存在,但不存在文件。显然,paste(a)会返回a而不是potential.xvg

我在一个单独的文件中定义了所有函数,我在开头提供了源代码,但我也尝试在主脚本中定义函数。

有什么问题?

-------更新1

我用这个函数解析参数(-d = value1):

parseArgs <- function(x) strsplit (sub("^-","",x), "=")   
argsDF <- as.data.frame(do.call("rbind", parseArgs(args)))
argsL <- as.list(as.character(argsDF$V2))
names(argsL) <- (argsDF$V1)

然后

if(is.null(argsL$x)) print("density file not supplied") else file.density <- argsDF$V2[which(argsDF$V1 == "x")] 

如果我使用exists("a")(或exists("file.density"))检查是否存在,则可以正常运行,但exists(a)会给我这个错误:

Error in exists(a) : invalid first argument

0 个答案:

没有答案
相关问题