将 if else 列表附加到矩阵或另一个容器(如数据框)中。使用循环排序并打印到矩阵中

Appending an if else list into a matrix or another container such as a dataframe. Sorting and printing into matrix with loop

假设我们有代码并想将打印输出到矩阵、数据框、向量或列表中。让我们

library(quantmod)    
StockList <- c("AAIT", "AAL",  "AAME", "AAOI", "AAON", "AAPC", "AAPL", "AAVL", "AAWW", "AAXJ")
s<-10
for (i in 1:length(StockList)){print(i)
get_fin<-tryCatch(lapply(StockList[i], function(x) getFinancials(x, auto.assign = FALSE)), error=function(e) NULL)                          
if(!is.null(get_fin)){
Keep<-print("Keep") 
}
else {Delete<-print("Delete")}}

将此输出转换为结构化矩阵:

[1] 1
[1] "Delete"
[1] 2
[1] "Keep"
[1] 3
[1] "Keep"
[1] 4
[1] "Keep"
[1] 5
[1] "Keep"
[1] 6
[1] "Delete"
[1] 7
[1] "Keep"
[1] 8
[1] "Keep"
[1] 9
[1] "Keep"
[1] 10
[1] "Keep"

下面的输出是我想要的:

    [1,]
[1,]"Delete"
[2,]"Keep"
[3,]"Keep"
[4,]"Keep"
[5,]"Keep"
[6,]"Delete"
[7,]"Keep"
[8,]"Keep"
[9,]"Keep"
[10,]"Keep"

以上是我想要的矩阵。我手动写出来的。如果能帮忙,谢谢!

尝试创建一个向量来保存结果并更改 if 语句以分配输出:

    StockList <- c("AAIT", "AAL",  "AAME", "AAOI", "AAON", "AAPC", "AAPL", "AAVL", "AAWW", "AAXJ")
 s<-10
 result <- c()
 for (i in 1:length(StockList)){print(i)
   get_fin<-tryCatch(lapply(StockList[i], function(x) getFinancials(x, auto.assign = FALSE)), error=function(e) NULL)                          
   if(!is.null(get_fin)){
     result[i] <- "Keep" 
   }
   else {result[i] <- "Delete"}}
 matrix(result, ncol=1)