I have the following dataframe:
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")
)
I want to fill Data$qtr with Year/Quater - f.e. 01/01 (I need this format!).
I wrote a function:
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)
But it does not work. I always get the error message:
Error in FUN(X[[1L]], ...) : Object 'y' not found
Why?
I have been loving the
lubridate
package for working with dates. Super slick. Thequarter
function finds the quarter (of course) and then just pair that with the year.If you are not familiar with the
%>%
the first line basically says "use data frame calleddata
" and the second line says "mutate (or add) a column calledqtr
"this gives the flexibility of returning any format back that has the quarter in it
no need for chron or zoo
as for your example
I made a similar format using quarters() and sub() in R:
Hope this helps!
Another (longer) way of doing it using if statements is this:
Returns a string in the format:
Then you could extend that using a loop.
Using base functions:
You need to explicilty
Vectorize
your function:However, when it comes to more or less standard tasks (such as datetime manipulations), there's always a solution already available:
To convert to your specific format, use