首页 > 解决方案 > aa数据框中的日期时间程序问题

问题描述

我被要求在实习期间编写一个函数,该函数通过带有日期和时间的数据框运行,并返回 20 小时之前的行的一些单元格。附上部分数据框的图片;ID 是动物的编号,Date 是看到动物的时间,Time 是看到动物的时间(例如:2 代表 2 小时),Lat 和 Long 是动物的坐标。

在此处输入图像描述

然后,该函数接受输入(ID、日期+时间)并返回动物 20 小时前所在位置的坐标(数据框的第 4 和 5 列)。

错误信息总是一样的:

打印错误(X):找不到对象“X”

似乎 IF 子句中的条件永远不会重新统一......

这是脚本:

data <- data.frame(GPS_data_for_R) #data contains the excel spreadsheet
data$NewTime <- ymd_h(paste(data$Date,as.character(data$Time))) #a new column is created that merge the Date and the Time columns into a POSIXct format

# This function returns the coordinates of the animal 20h before, depending on the ID, Dtae and Time the user wants
Feeding_coordinates <- function (ID, NewTime){
    for ( i in (1:length(data) ) ) {
      if ( data[i,1] == ID & data[i,6] == as.POSIXct(NewTime,format="%Y-%m-%d %H:%M:%OS", tz="UTC")-72000){ #if the ID of the animal matches the request and if the NewTime - 20h also
        data[i,4] <- X #then X takes the value of the Longitude
        data[i,5] <- Y }# and Y the value of the Lagitude
  }
  print (X)
  print (Y)
}

我真的不知道为什么它不起作用,所以非常欢迎任何帮助,我已经花了这么多时间!

谢谢你,曼农。

标签: rdatedataframetimeposix

解决方案


由于(尚未)提供(样本)数据,因此很难为您提供帮助。但是,如果您的数据的结构使得每一行都类似于一小时,并且您希望从 20 小时前获取该行,则可能需要使用dplyr's lag()

library(dplyr)
data %>%
 group_by(ID) %>% # Perhaps optional
 mutate(feed_coord_lat=lag(Lat, 20),
        feef_coord_long=lag(Long, 20))

这为您提供了具有两个滞后坐标列的整个数据框。您也可以从中构建一个函数。


推荐阅读