[英]R Programming: Append data in a dataframe within running nested loops
我有以下代碼。
for(i in seq(from=1, to=8, by=1)) #i is number of stocks from a list
{
for(j in seq(from=1, to=8, by=1)) #j is number of trading days from another list
{
## Matching bid and ask prices of each stock for each date and update temp_table
select_output <- sqldf("select * from temp_table where FLAG == 'new' ")
}
}
在當前情況下,僅最后的迭代數據保留在預期的select_output
中。 我想保持文件打開狀態,以所有迭代中的數據填充文件。 我不想使用另一個循環將數據插入到select_output
。 R中還有其他方法嗎? 如果可能,請提出建議。
提前致謝。
一種選擇是組合expand.grid,apply和do.call
index <- expand.grid(
i = 1:8,
j = 1:8
)
results <- apply(index, 1, function(x){
x["i"] # holds i
x["j"] # holds j
sqldf("select * from temp_table where FLAG == 'new' ")
})
do.call(rbind, results)
我認為這實際上是R的弱點。 最好的辦法可能是:
results <- data.frame(a=numeric(0), b=character(0), ...) # whatever columns you expect
for(i in 1:8) for(j in s1:7) {
## Your code...
select_output <- sqldf("select * from temp_table where FLAG == 'new' ")
results <- rbind(results, select_output)
}
這里的問題是您需要預先指定results
的格式。 這可能是一件好事-它使您可以清楚地說明期望的內容,如果違反了這些期望,則會出錯。 但是,最好有一種快速的方法來將數據幀綁定在一起。 也許Hadleyverse有解決方案?
這是另一種解決方案。
results <- lapply(1:8, function(i){
#do some stuff with i
output <- lapply(1:8, function(j){
#do some stuff with j based on the stuff with i
})
do.call(rbind, output)
})
do.call(rbind, results)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.