【问题标题】:Problem with date an time program in a a dataframe数据框中的日期和时间程序问题
【发布时间】:2018-11-26 13:08:20
【问题描述】:

我被要求在实习期间编写一个函数,该函数通过带有日期和时间的数据框运行,并返回 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)
}

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

谢谢你, 马农。

【问题讨论】:

  • 欢迎来到 SO。图片既不是代码也不是数据,除非主题是图像处理。请单击您的问题下方的“r”,然后单击“信息”选项卡并阅读那里提供的提示(一些通过链接),了解如何制作一个包含真实数据的好问题,所有正在使用的 R 包和完整(但最少)可重现的代码,以帮助他人帮助您。

标签: r date dataframe time posix


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2021-11-23
    相关资源
    最近更新 更多