为什么这些R命令在脚本与命令行中的行为不同?

时间:2016-01-03 00:44:52

标签: r

我已经在我的Window 7 RStudio环境(R版本3.2.3)中编写了一个脚本,我看到了在命令行上看到的行为与行为之间的差异从脚本中运行相同的命令。这是我运行的脚本的简化版本:

if(!require(lubridate)) { install.packages("lubridate"); require(lubridate) }
startDate <- "2015-12-21"
endDate <- "2016-01-03"

rDateStrangeness <- function(startDate = "2015-12-21",
                             endDate = "2016-01-03") {
    sdate <- as.Date(startDate)
    edate <- as.Date(endDate)
    intervalDays <- seq(sdate, edate, by="days")
    for(day in intervalDays) {
        cat("day = ", day, ", as.character.Date(day) = ",
            as.character.Date(day) , ", wday(day) = ", wday(day), "\n")
    }
}

当我获取并运行rDateStrangeness()时,我得到了这个输出:

day =  16790 , as.character.Date(day) =  16790 , wday(day) =  16790
day =  16791 , as.character.Date(day) =  16791 , wday(day) =  16791
day =  16792 , as.character.Date(day) =  16792 , wday(day) =  16792
day =  16793 , as.character.Date(day) =  16793 , wday(day) =  16793
day =  16794 , as.character.Date(day) =  16794 , wday(day) =  16794
day =  16795 , as.character.Date(day) =  16795 , wday(day) =  16795
day =  16796 , as.character.Date(day) =  16796 , wday(day) =  16796
day =  16797 , as.character.Date(day) =  16797 , wday(day) =  16797
day =  16798 , as.character.Date(day) =  16798 , wday(day) =  16798
day =  16799 , as.character.Date(day) =  16799 , wday(day) =  16799
day =  16800 , as.character.Date(day) =  16800 , wday(day) =  16800
day =  16801 , as.character.Date(day) =  16801 , wday(day) =  16801
day =  16802 , as.character.Date(day) =  16802 , wday(day) =  16802
day =  16803 , as.character.Date(day) =  16803 , wday(day) =  16803

但是当我从命令行运行相同的命令时

> sdate <- as.Date(startDate)
> edate <- as.Date(endDate)
> intervalDays <- seq(sdate, edate, by="days")
> day <- intervalDays[1]
> day.aschar <- as.character.Date(day)

我看到了这个输出

> day.aschar
[1] "2015-12-21"
> class(day.aschar)
[1] "character"
> wday(day.aschar)
[1] 2

我期待在命令行中看到的行为,但看起来循环访问日期序列的方式与我期望的方式有所不同。我想在循环中运行 wday ,但它不能处理循环如何索引到日期序列中。

为什么我看到命令行和脚本之间的这些差异以及如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

深入研究,看起来R在脚本中创建了一个数字迭代器,这不是我期望或想要的行为。我在这篇相关文章中找到了答案:

Looping over a datetime object results in a numeric iterator

具体来说,我稍微改变了循环,如下所示得到了我的目标:

for(i in seq_along(intervalDays)) {
    day <- intervalDays[i]
    cat...
}

答案 1 :(得分:1)

如果你改变

怎么样?
nil

intervalDays <- seq(sdate, edate, by="days")

这里我们实际上将for循环无法处理的Date向量更改为for循环可以管理的字符向量。

intervalDays <- as.character(seq(sdate, edate, by="days"))