【发布时间】:2021-11-03 20:03:32
【问题描述】:
我有两个单独的 while 语句,但是相互依赖我需要合并它们。根据这个stackoverflow 的回答,这应该很简单。但是,我尝试的方法不起作用。
在分隔的while 语句下方(使用 cmets):
library(svDialogs)
library(quantmod)
# List of data.frame names
loadedDataframes <- names(which(unlist(eapply(.GlobalEnv,is.data.frame))))
# ask user to enter a ticker
ticker <- toupper(dlgInput(paste("Enter a ticker (these are already loaded:", toString(stripExtension), ")"), "e.g., AAPL")$res)
# check if ticker already loaded as ```data.frame```
existsTicker <- exists(ticker)
# while loop until a not loaded data.frame ticker is typed
while (existsTicker == TRUE){
# Ask ticker again
ticker <- toupper(dlgInput(paste("Please enter a ticker that has not yet been loaded:", toString(stripExtension), ")"), "e.g., AAPL")$res)
# Check if ticker exists and load value in existsTicker
existsTicker <- exists(ticker)
}
# get some stock prices from default service
yahooSymbol <- getSymbols.yahoo(ticker, env = globalenv())
# Close an open internet connection
# If getSymbols.yahoo has an unknown ticker, it leaves connection to Yahoo! open
closeAllConnections()
# Check if yahooSymbol returned a character(0) and if true
# ask for an existing ticker at Yahoo! Finance
while (identical(yahooSymbol, character(0)) == TRUE) {
# Ask for an existing ticker at Yahoo! Finance
ticker <- toupper(dlgInput(paste("Please enter an existing ticker at Yahoo! Finance, except: ", toString(loadedDataframes), ")"))$res)
# Check if ticker exists and load value in existsTicker
yahooSymbol <- getSymbols.yahoo(ticker, env = globalenv())
}
下面是两个while 条件的初步合并,根据提到的stakoverflow post。但是,无论符号(无论是否存在),代码似乎都没有“反应”(因为没有更好的术语):
# Merge two conditions into one while loop
while (existsTicker == TRUE && identical(yahooSymbol, character(0)) == TRUE) {
# Ask ticker again
ticker <- toupper(dlgInput(paste("Please enter a ticker that has not yet been loaded:", toString(stripExtension), ")"), "e.g., AAPL")$res)
# Check if ticker exists and load value in existsTicker
existsTicker <- exists(ticker)
# Check if ticker exists and load value in existsTicker
yahooSymbol <- getSymbols.yahoo(ticker, env = globalenv())
}
任何帮助表示赞赏。
使用的系统:
- R 版本:4.1.1 (2021-08-10)
- RStudio 版本:1.4.1717
- 操作系统:macOS Catalina 版本 10.15.7
【问题讨论】:
标签: r while-loop