簡體   English   中英

在R中使用switch語句

[英]Using Switch Statement in R

我知道R中的switch語句並非旨在像在C ++中那樣工作,但是我已經閱讀了文檔並且似乎無法弄清楚為什么以下內容不起作用

file.types <- c('bmp', 'jpeg', 'png', 'tiff', 'eps', 'pdf', 'ps')
  if(tolower(file.type) %in% file.types) {
    switch(file.type,
           bmp = bmp(filename=paste(file.location, file.name, '.',
                                    file.type, sep=''), 
                     width=res[2], height=res[1])
           jpeg = jpeg(filename=paste(file.location, file.name, '.',
                                      file.type, sep=''),
                     width=res[2], height=res[1])
           png = png(filename=paste(file.location, file.name, '.',
                                    file.type, sep=''),
                     width=res[2], height=res[1])
           tiff = tiff(filename=paste(file.location, file.name, '.',
                                      file.type, sep=''),
                       width=res[2], height=res[1])
           eps = postscript(filename=paste(file.location, file.name, '.',
                                           file.type, sep=''),
                            width=res[2], height=res[1])
           pdf = postscript(filename=paste(file.location, file.name, '.',
                                           file.type, sep=''),
                            width=res[2], height=res[1])
           ps = postscript(filename=paste(file.location, file.name, '.',
                                          file.type, sep=''),
                           width=res[2], height=res[1]))  
  } else {
      stop(paste(file.type,' is not supported', sep=''))
  }

當file.type為'jpeg'時出現以下錯誤

Error: unexpected symbol in:
"           bmp = {bmp(filename=paste(file.location, file.name, '.', file.type, sep=''), width=res[2], height=res[1])}
       jpeg"

感謝任何見識!

這是語法錯誤。 你是缺少一個,在每個選項在結束(逗號) switch ,如

switch(file.type,
       bmp = bmp(filename=paste(file.location, file.name, '.', 
                                file.type, sep=''), 
                 width=res[2], height=res[1]),
                                             ^ here

一般形式是

switch(foo,
       opt1 = statement1,
       opt2 = statement2,
       opt3 = ,
       opt4 = statement3)

opt3opt4返回statement3的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM