使用for循环从

时间:2016-04-06 19:32:48

标签: r

我找到了post on reddit,它让我想到如何使用for循环从上面的行中获得差异。我尝试了下面的方法,但并不是很好。有没有更好的方法来获得上面的行,日期或数字的差异?

test <- data.frame(Dates=rbind("2006-08-07 19:33:02","2006-08-07 19:34:02","2006-10-10 19:33:02","2006-10-11 19:34:02" ,"2006-10-12 19:34:02","2006-10-13 19:34:02","2006-10-14 19:34:02"))


for (i in 2:nrow(Dates)){
  difftime(i[2-1,],i)
}

2 个答案:

答案 0 :(得分:1)

确保将日期转换为实际日期格式

test <- data.frame(Dates=rbind("2006-08-07 19:33:02","2006-08-07 19:34:02","2006-10-10 19:33:02","2006-10-11 19:34:02" ,"2006-10-12 19:34:02","2006-10-13 19:34:02","2006-10-14 19:34:02"))

df <- test %>% mutate( Dates = as.POSIXct(Dates),
                       Diff = Dates - lag(Dates) )
df
                Dates       Diff
1 2006-08-07 19:33:02    NA mins
2 2006-08-07 19:34:02     1 mins
3 2006-10-10 19:33:02 92159 mins
4 2006-10-11 19:34:02  1441 mins
5 2006-10-12 19:34:02  1440 mins
6 2006-10-13 19:34:02  1440 mins
7 2006-10-14 19:34:02  1440 mins

答案 1 :(得分:1)

由于许多R函数都是矢量化的,因此根本不需要循环。

试试这个:

test <- data.frame(Dates=rbind("2006-08-07 19:33:02","2006-08-07 19:34:02","2006-10-10 19:33:02","2006-10-11 19:34:02" ,"2006-10-12 19:34:02","2006-10-13 19:34:02","2006-10-14 19:34:02"))

test$Dates <- as.POSIXct(test$Dates)

diff(test$Dates)

结果:

Time differences in mins
[1]     1 92159  1441  1440  1440  1440