我有以下數據框:格式日期年度/季度
Data <- data.frame(
date = c("2001-01-01", "2001-02-01", "2001-03-01", "2001-04-01", "2001-05-01", "2001-06-01"),
qtr = c("NA", "NA","NA","NA","NA","NA")
)
我要填寫數據$ QTR與年/四 - F.E. 01/01(我需要這種格式!)。
我寫了一個函數:
fun <- function(x) {
if(x == "2001-01-01" | x == "2001-02-01" | x == "2001-03-01") y <- "01/01"
if(x == "2001-04-01" | x == "2001-05-01" | x == "2001-06-01") y <- "01/02"
return(y)
}
n$qtr <- sapply(n$date, fun)
但它不工作。我總是得到錯誤信息:
Error in FUN(X[[1L]], ...) : Object 'y' not found
爲什麼?
你可能得到這個錯誤是因爲你的日期之一在'if'表達式中沒有匹配。所以'y'從來沒有被指定爲'樂趣'。 –