![](/img/trans.png)
[英]Check unique values in multiple columns (treated as one big 'column') in 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! 下載符號。
我的問題:
使用的系統:
問題來自這樣一個事實,即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.