如何使用grepl检测缺少的字符

时间:2018-04-11 22:11:01

标签: r

我正在尝试下面的代码,以便如果既没有“/”也没有“\”输出是错误而应用程序停止,但它不起作用。我看不出它有什么问题。

 if (grepl("/", OUTpath, fixed=TRUE)) { # mac style
     OUTpath<- paste(paste(unlist(strsplit(OUTpath, "/", fixed=TRUE)), collapse="/"), "/", sep="")
   } else 
     if (grepl("\\", OUTpath, fixed=TRUE)) { # windows style
       OUTpath<- paste(paste(unlist(strsplit(OUTpath, "\\", fixed=TRUE)), collapse="\\"), "\\", sep="")
     } else
       if(!grepl("/", OUTpath, fixed=TRUE) || !grepl("\\", OUTpath, fixed=TRUE)){
       trueFalse = FALSE
       errorMessage("Unrecognized path separator in OUTpath or no path specification in PARAMS file. Cannot open connection\n
                             You can edit your input file and save the changes. Afterwards, stop and restart glycoPipe and upload file again")
       stop("Unrecognized path separator in OUTpath\n")
     }

1 个答案:

答案 0 :(得分:0)

这是我的最终目的。我删除了一个嵌套的if语句。我也改变了花括号。不太确定这适用于您的应用程序,也许您可​​以包含更多详细信息。

OUTpath <- 'aa' # Gives error
OUTpath <- 'aa\\aa' # Produces 'aa\\aa\\'
OUTpath <- 'aa\aa' # Produces error
OUTpath <- 'aa/aa' # Produces 'aa/aa/'

if (grepl("/", OUTpath, fixed=TRUE)) { # mac style
  OUTpath<- paste(paste(unlist(strsplit(OUTpath, "/", fixed=TRUE)), collapse="/"), "/", sep="")
} else {
  if (grepl("\\", OUTpath, fixed=TRUE)) { # windows style
    OUTpath<- paste(paste(unlist(strsplit(OUTpath, "\\", fixed=TRUE)), collapse="\\"), "\\", sep="")
  } else {
  #  if(!grepl("/", OUTpath, fixed=TRUE) || !grepl("\\", OUTpath, fixed=TRUE)){
      trueFalse = FALSE
      errorMessage("Unrecognized path separator in OUTpath or no path specification in PARAMS file. Cannot open connection\n
                   You can edit your input file and save the changes. Afterwards, stop and restart glycoPipe and upload file again")
      stop("Unrecognized path separator in OUTpath\n")

  }
}

更新

您应该使用file.path()函数创建独立于OS的路径。

file.path(getwd(), 'lala', 'ee')
[1] "C:/Users/Matias/Desktop/lala/ee"