Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么';t rbind()是否在for循环中工作?_R_Loops_Rbind - Fatal编程技术网

为什么';t rbind()是否在for循环中工作?

为什么';t rbind()是否在for循环中工作?,r,loops,rbind,R,Loops,Rbind,我有一系列的日期: date_rng <- seq( as.Date("2008-01-01"), as.Date("2008-12-31"), by="+1 day") 但是绑定没有发生,我只剩下范围中第一个日期的原始数据帧,它是在for循环之前创建的 不过,这是可行的: atl_weather <- get_table("ATL", date_rng[1]) new_df <- get_table("ATL", date_rng[2]) new_df <- scra

我有一系列的日期:

date_rng <- seq( as.Date("2008-01-01"), as.Date("2008-12-31"), by="+1 day")
但是绑定没有发生,我只剩下范围中第一个日期的原始数据帧,它是在for循环之前创建的

不过,这是可行的:

atl_weather <- get_table("ATL", date_rng[1])
new_df <- get_table("ATL", date_rng[2])
new_df <- scraped_data_formatter(new_df, date_rng[2])
rbind(atl_weather, new_df)

atl_weather它确实有效。问题是您正在丢弃结果,因为您没有将
rbind()
的输出分配给任何对象

改变

rbind(atl_weather, get_table("ATL", d), d)
对此

atl_weather <- rbind(atl_weather, get_table("ATL", d), d)
atl_weather每当我被迫在for循环中建立数据帧时,我都会给你我最喜欢的编程模式来使用,这可能会偏离主题(因为问题已经得到了正确的回答):

for (d in as.list(date_rng[2:4])){
    if (exists("atl_weather")) {
        atl_weather = rbind(atl_weather, get_table("ATL", d), d)
    } else {
        atl_weather = get_table("ATL", d)
    }
}
当然,如果我的函数包含在
get_table
中,我会使用某种
apply
语句。但是,当现实生活遇到阻碍,而for循环的内部太复杂时,我通常会有某种
temp.data.frame
对象,它被分配或绑定到
atl_weather
,使用与上述类似的模式:

if (exists("atl_weather")) rm(atl_weather) # in case I'm dynamically running code in chunks

for (d in as.list(date_rng[2:4])){
    temp.df = ... # complicated stuff

    if (exists("atl_weather")) {
        atl_weather = rbind(atl_weather, temp.df)
    } else {
        atl_weather = temp.df
    }
}

您需要将
rbind()
分配给数据:
atl\u是将基本df合并到for循环中的一种方法。关于陷入困境,您是对的。我不知道数据刮取的效率有多高,也没有多少经验,但理想情况下,我想做的是在每次调用get_table()时将数据写入SQL数据库。这至少会使以后检索数据更高效。对于一个机场,在亚特兰大的例子中,效率并不太低,但我有很多机场需要运行此代码。您知道
merge()
是否可以正常工作,并且比
rbind()
更高效?
for (d in as.list(date_rng[2:4])){
    if (exists("atl_weather")) {
        atl_weather = rbind(atl_weather, get_table("ATL", d), d)
    } else {
        atl_weather = get_table("ATL", d)
    }
}
if (exists("atl_weather")) rm(atl_weather) # in case I'm dynamically running code in chunks

for (d in as.list(date_rng[2:4])){
    temp.df = ... # complicated stuff

    if (exists("atl_weather")) {
        atl_weather = rbind(atl_weather, temp.df)
    } else {
        atl_weather = temp.df
    }
}