我正在嘗試將包中的函式應用于我的資料框的某些列。包鏈接在這里。
但是,包的作者使用了簡單的 if 陳述句,由于矢量化條件,它不允許我使用 apply 函式。我的問題是專門修復此功能,以便我可以在應用功能中使用它。
主要有 4 個 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
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/482619.html
下一篇:跨行的條件突變(按組/ID)?
