r语言 - 具有多个值更改的if语句的矢量化输入(使函数可以与apply一起使用)



我试图从包应用函数到我的数据框架的某些列。包的链接在这里。

然而,包的作者使用了简单的if语句,由于矢量化的条件,它不允许我使用apply函数。我的问题是专门修复这个函数,以便我可以在应用函数中使用它。

有四个if语句需要寻址:

1:

if (month < 1 | month > 12)
stop("month is outside the range 1-12")
if (day < 1 | day > 31)
stop("day is outside the range 1-31")

2:

if (month < 7)
{
days <- days + 31 * (month -1 )
} else{
days <- days + 186 + 30 * (month - 7)
}
3:

if (days > 36524)
{
days <- days - 1
gyear <- gyear + 100 * (days %/% 36524)
days <- days %% 36524
if (days >= 365)
days <- days + 1
}

4:

if (days > 365)
{
gyear <- gyear + ((days - 1) %/% 365)
days <- (days - 1) %% 365
}

现在我知道我可以用简单的ifelse语句来修复其中的一些问题,但是我看到人们避免在ifelse语句中分配变量,我更喜欢使用一般的方法来修复这个问题。此外,dplyr的case_when也不能普遍应用。有没有人可以帮我用一种比较普遍、比较有效的方法来解决这个问题?

编辑-根据MrFlick的评论,这就是我打算如何使用该功能我的数据框中有原始日期,以月为单位(求和为总月)

convert_date_to_greg <- function(x){
year = floor(as.numeric(x)/12)
month = (as.numeric(x)%%12)+1
day = 1 
ifelse(is.na(x)==FALSE,return(jal2greg(year,month,day,asDate = T)),return(NA))
}
greg_convert <- lapply(date_sorted_df[,date_column_indices],
FUN=convert_date_to_greg)

这是一个示例输入:

df<- data.frame(date_1=c(16735,16234,17123,16123), date_2=c(16352,16352,16666,17124))

但是,使用apply,我会看到以下错误消息:

条件长度为>1

apply()型函数为向量化函数;它们不应该与这样的函数一起使用。您可能需要修复该功能或使用apply()以外的解决方案。

我建议修复函数(R代码应该尽可能向量化)。对于1,您只需要检查是否有任何输入无效。对于2-4,ifelse()将有帮助。

1:

if (sum(month < 1 | month > 12) != 0) { stop("a month is outside the range 1-12") }
if (sum(day < 1 | day > 31) != 0) { stop("a day is outside the range 1-31") }

2:

days <- ifelse(month < 7, days + 31 * (month -1 ), days + 186 + 30 * (month - 7))

3:

days <- days - 1
gyear <- gyear + 100 * (days %/% 36524)
days <- days %% 36524
days <- ifelse(days >= 365, days <- days + 1, days)     

4:

gyear <- ifelse(days > 365, gyear + ((days - 1) %/% 365, gyear)
days  <- ifelse(days > 365, (days - 1) %% 365, days)

最新更新