【问题标题】:Allow user to input multiple values to be treated in while statement with R允许用户在使用 R 的 while 语句中输入要处理的多个值
【发布时间】:2021-11-20 12:33:07
【问题描述】:

感谢here 找到的解决方案,用户可以输入代码/符号,然后在本地和互联网上检查其可用性。如果前者是和/或后者不是,则再次询问用户输入,否则从互联网下载:

# load packages
library(svDialogs)
library(quantmod)

# start a loop; we'll find out if we need to exit based on user feedback
while (TRUE) {
  # get a potential ticker value from the user
  ticker <- toupper(dlgInput("Please enter a ticker that has not yet been loaded:")$res)
  
  # if this value already exists in global environment, immediately go back to
  # the beginning of the loop
  if (exists(ticker)) next
  
  # check Yahoo to see if the ticker is valid and if so get the results
  yahooSymbol <- getSymbols.yahoo(ticker, env = globalenv())
  
  # if yahoo returned a response, exit the loop
  if (!identical(yahooSymbol, character(0))) break
}

但是,当用户输入多个代码/符号时,代码会失败。尽管如此,当代码在while 语句之外运行时,它能够处理多个代码/符号(找到here 的解决方案的一部分):

# load packages
library(svDialogs)
library(quantmod)
library(stringr)

# get tickers from user
ticker <- toupper(dlgInput("Please enter one or more tickers separated by comma.")$res)

# split tickers
tickers <- unlist(strsplit(gsub(" ", "", ticker, fixed = TRUE), ","))

# download from Yahoo!
yahooSymbol <- getSymbols.yahoo(tickers, env = globalenv())

# close all open Internet connections (as a precaution)
closeAllConnections()

所以我认为如果上面的代码有效,为什么不在 while 语句中,例如:

# load packages
library(svDialogs)
library(quantmod)
library(stringr)

while (TRUE) {

# get one or many tickers
ticker <- toupper(str_trim(dlgInput("Enter one or more new or not loaded tickers separated with comma.")$res))

# split tickers
tickers <- unlist(strsplit(gsub(" ", "", ticker, fixed = TRUE), ","))

  # check locally if already loaded
  if (exists(tickers)) next

  # download from Yahoo!      
  yahooSymbol <- getSymbols.yahoo(tickers, env = globalenv())
  
  # if yahoo returned a response, exit the loop
  if (!identical(yahooSymbol, character(0))) break
}

不用说/写我在Error in exists(tickers) : first argument has length &gt; 1 上惨败。然而,当我引用if (exists(tickers)) next,小胜利时,yahooSymbol &lt;- getSymbols.yahoo(tickers, env = globalenv()) 确实从 Yahoo! 下载了符号!

我的问题:

  • 如何更正上面的代码,以便循环验证代码的存在并从 Yahoo! 下载代码。如果它们存在?

使用的系统:

  • R 版本:4.1.1 (2021-08-10)
  • RStudio 版本:1.4.1717
  • 操作系统:macOS Catalina 版本 10.15.7 和 macOS Big Sur 版本 11.6

【问题讨论】:

    标签: r loops conditional-statements


    【解决方案1】:

    问题在于exists 只测试单个对象的存在。

    试一试

    exists(c("a", "b"))
    

    您将遇到导致代码崩溃的相同错误。

    要解决您的问题,请尝试

    if (all(sapply(tickers, exists))) next
    
    • sapply 将允许您将函数 exists “应用”到 tickers 中的所有元素,
    • all 将判断sapply 给出的结果向量是否仅由TRUEs 组成。

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2020-02-21
      • 2018-09-30
      相关资源
      最近更新 更多