我有一个非常大的数据集,其中包含一个
我创建了4个函数:
- 3个子函数,以便我可以使用 *apply 函数进行逻辑比较和选择 - 1个函数用于确定季节
以下是这些函数:
DateTime
列,其值为 POSIXct。我需要根据 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)
我会感激任何帮助,这让我很疯狂!