gpt4 book ai didi

r - 使用R中的lubridate从日期确定季节

转载 作者:行者123 更新时间:2023-12-04 11:36:31 24 4
gpt4 key购买 nike

我有一个很大的数据集,其中的DateTime列包含POSIXct-Values。我需要根据DateTime列确定季节(冬季-夏季)。我创建了一个在小型数据集上可以正常运行的函数,但是在大型数据集上使用时会崩溃。有人可以看到我的错误吗?

我创建了4个函数:


3个子功能,使我可以进行逻辑比较和选择
使用* apply函数
1确定季节的功能


功能如下:

require(lubridate)

# function for logical comparison (to be used in *apply)
greaterOrEqual <- function(x,y){
ifelse(x >= y,T,F)
}

# function for logical comparison (to be used in *apply)
less <- function(x,y){
ifelse(x < y,T,F)
}

# function for logical comparison (to be used in *apply)
selFromLogic <- function(VecLogic,VecValue){
VecValue[VecLogic]
}

# Main Function to determine the season
getTwoSeasons <- function(input.date) {
Winter1Start <- as.POSIXct("2000-01-01 00:00:00", tz = "UTC")
Winter1End <- as.POSIXct("2000-04-15 23:59:59", tz = "UTC")

SummerStart <- Winter1End + 1
SummerEnd <- as.POSIXct("2000-10-15 23:59:59", tz = "UTC")

Winter2Start <- SummerEnd + 1
Winter2End <- as.POSIXct("2000-12-31 00:00:00", tz = "UTC")

year(input.date) <- year(Winter1Start)
attr(input.date, "tzone") <- attr(Winter1Start, "tzone")

SeasonStart <- c(Winter1Start,SummerStart,Winter2Start)
SeasonsEnd <- c(Winter1End,SummerEnd,Winter2End)
Season_names <- as.factor(c("WinterHalfYear","SummerHalfYear","WinterHalfYear"))

Season_select <- sapply(SeasonStart, greaterOrEqual, x = input.date) & sapply(SeasonsEnd, less, x = input.date)
Season_return <- apply(Season_select,MARGIN = 1,selFromLogic,VecValue = Season_names)

return(Season_return)
}


这是测试功能的一种方法:

dates <- Sys.time() + seq(0,10000,10)
getTwoSeasons(dates)


我将不胜感激,这让我发疯!

最佳答案

如果您有兴趣找回四个季节,请使用以下代码:

library(lubridate)
getSeason <- function(input.date){
numeric.date <- 100*month(input.date)+day(input.date)
## input Seasons upper limits in the form MMDD in the "break =" option:
cuts <- base::cut(numeric.date, breaks = c(0,319,0620,0921,1220,1231))
# rename the resulting groups (could've been done within cut(...levels=) if "Winter" wasn't double
levels(cuts) <- c("Winter","Spring","Summer","Fall","Winter")
return(cuts)
}


单元测试:

getSeason(as.POSIXct("2016-01-01 12:00:00")+(0:365)*(60*60*24))

关于r - 使用R中的lubridate从日期确定季节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36502140/

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