FOR循环以计算R中日期的差异 [英] FOR loop to calculate difference on dates in R
问题描述
我正在尝试计算以天为单位的数据帧中两个日期之间的差异,并将其保存在同一数据帧的称为延迟的另一列中.这是我的代码,但是不起作用:
I am trying to calculate the difference between two dates in a data frame in days and save it in another column of the same data frame called lag. This is my code but it is not working:
Daily_Streamflow$Date
Daily_Streamflow$lag[1] <- 0
j <- 2
for (j in length(Daily_Streamflow$Date)) {
Daily_Streamflow$lag[j] <- as.numeric(difftime(Daily_Streamflow$Date[j],Daily_Streamflow$Date[j-1], unit=c("days")))
j <- j + 1
}
这是我的数据框的外观:
This is how my data frame looks:
当我将第一天的差值设置为 Daily_Streamflow $ lag [1]
等于0时,所有剩余值都设置为0.如果我将此值保留为空,则该列的所有值设置为 NA
.看起来,虽然j值增加并且循环运行,但是代码将第一个滞后值赋给了所有列,忽略了for内部的函数.
When I set the difference for the first day Daily_Streamflow$lag[1]
equal to 0 all the remaining values are set to 0. If I keep this value empty, all the values of the column are set to NA
. It seems that the code put the value of the first lag to all the column, omitting the function inside the for, though the j value increases and the loop runs.
推荐答案
由于您没有为我们提供数据,因此您必须自己进行测试:
Since you didn't provide data for us, you have to test this by yourself:
Daily_Streamflow$Date
Daily_Streamflow$lag[1] <- 0
for (j in 2:length(Daily_Streamflow$Date)) { # add 2: to create a sequence
Daily_Streamflow$lag[j] <- as.numeric(difftime(Daily_Streamflow$Date[j],Daily_Streamflow$Date[j-1], units=c("days")), units = "days") # change 'unit' to 'units' and add 'units' attribute to the 'as.numeric' function as well
j <- j + 1
}
这篇关于FOR循环以计算R中日期的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!