簡體   English   中英

允許用戶輸入多個值以在 while 語句中處理 R

[英]Allow user to input multiple values to be treated in while statement with R

多虧了這里找到的解決方案,用戶可以輸入代碼/符號,然后在本地和 Inte.net 上檢查其可用性。 如果前者是和/或后者不是,則再次詢問用戶輸入,否則從 Inte.net 下載:

# 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語句之外運行時,它能夠處理多個代碼/符號(此處找到的部分解決方案):

# 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 > 1 然而,當我引用if (exists(tickers)) next時,小勝利, yahooSymbol <- getSymbols.yahoo(tickers, env = globalenv())仍然從 Yahoo! 下載符號。

我的問題:

  • 如何更正上面的代碼,使其既循環驗證代碼的存在又從雅虎下載它們? 如果他們存在?

使用的系統:

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

問題來自這樣一個事實,即exists僅測試單個 object 的存在。

嘗試例如

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

你會得到同樣的錯誤,使你的代碼崩潰。

要解決您的問題,請嘗試

if (all(sapply(tickers, exists))) next
  • sapply將允許您將 function exists “應用”到tickers中的所有元素,
  • all將判斷sapply給出的結果向量是否僅由TRUE組成。

暫無
暫無

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

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