gpt4 book ai didi

r - 如何在 R 中查找值

转载 作者:行者123 更新时间:2023-12-04 10:54:06 25 4
gpt4 key购买 nike

谁能帮忙,我有一个数据框( set_rise ),每一行包含当天的日落时间和第二天的日出时间。我有第二个数据框( data ),其中有一列日期/时间。我想在 data 中创建第二列通过获取 data 中的日期/时间,使用对应于白天或夜晚的字母并检查它是否在 set_rise 中的任何时间之间.

#df1- sunset, sunrise times
set_rise
set rise
1 2013-03-01 18:28:00 2013-03-02 08:27:00
2 2013-03-02 18:31:00 2013-03-03 08:23:00
3 2013-03-03 18:35:00 2013-03-04 08:19:00
4 2013-03-04 18:38:00 2013-03-05 08:15:00
5 2013-03-05 18:42:00 2013-03-06 08:12:00
6 2013-03-06 18:45:00 2013-03-07 08:08:00

#df2 my data
timedate
1 2013-03-01 19:00:00
2 2013-03-03 10:00:00
3 2013-03-06 00:01:00

我想要这样的输出
data
timedate night_day
2013-03-01 19:00:00 N
2013-03-03 10:00:00 D
2013-03-06 00:01:00 N

输出输入(set_rise)
dput(set_rise)
structure(list(set = structure(list(sec = 0, min = 28L, hour = 18L,
mday = 1L, mon = 2L, year = 113L, wday = 5L, yday = 59L,
isdst = 0L, zone = "WET", gmtoff = NA_integer_), .Names = c("sec",
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst",
"zone", "gmtoff"), class = c("POSIXlt", "POSIXt")), rise = structure(list(
sec = 0, min = 27L, hour = 8L, mday = 2L, mon = 2L, year = 113L,
wday = 6L, yday = 60L, isdst = 0L, zone = "WET", gmtoff = NA_integer_), .Names = c("sec",
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst",
"zone", "gmtoff"), class = c("POSIXlt", "POSIXt")), night = "N"), .Names = c("set",
"rise", "night"), row.names = 1L, class = "data.frame")

来自 dput(data) 的输出
dput(data)
structure(list(timedate = structure(c(1362873600, 1362960000,
1364342400), class = c("POSIXct", "POSIXt"))), .Names = "timedate", row.names = c(NA,
-3L), class = "data.frame")

最佳答案

这需要一些准备,但速度非常快。首先,您转换您的 set_risePOSIXct (而不是 POSIXlt )。接下来,将日期转换为 numeric并结合所有的值,使它们形成白天和黑夜的交替值。然后,您调用findInterval告诉你 data 的每个日期的间隔落入:如果间隔是奇数,则为夜晚,否则为白天。所以:

#convert to POSIXct
set_rise[]<-lapply(set_rise,as.POSIXct)
#combine all the numeric values together
intervals<-c(t(matrix(c(as.numeric(set_rise$set),as.numeric(set_rise$rise)),ncol=2)))
#call findInterval and set the values, checking the parity
c("D","N")[1+(findInterval(as.numeric(data$timedate),intervals) %% 2)]
#[1] "N" "D" "N"

关于r - 如何在 R 中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30595422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com