Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

enter image description here

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
145 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...