r - 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)
}
我真的不知道为什么它不起作用,所以非常欢迎任何帮助,我已经花了这么多时间!
谢谢你,曼农。
解决方案
由于(尚未)提供(样本)数据,因此很难为您提供帮助。但是,如果您的数据的结构使得每一行都类似于一小时,并且您希望从 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))
这为您提供了具有两个滞后坐标列的整个数据框。您也可以从中构建一个函数。
推荐阅读
- visual-studio - Visual Studio 2019:调试期间“本地”面板出错 - “检索本地值的内部错误”
- react-native - React-Redux 不更新 SetInterval 上的值
- postgresql - 返回单个值 PSQL - 查询没有结果数据的目的地
- php - 如何在 Wordpress rest_api_init 回调函数中传递参数
- javascript - 如何将图像上传到画布并在其上绘制正方形并获取正方形的坐标
- r - 如何left_join()两个数据集,但仅从其中一个数据集中选择特定列?
- c# - 如何从缓冲区中读取 x 数量
- spring-boot - Spring boot JSF可执行JAR找不到xhtml文件
- android - Android - 从 pageView 中删除对象会导致空白
- javascript - Cors cookie 和 ASP.NET