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?
A quarter refers to one-fourth of a year and is typically expressed as Q1 for the first quarter, Q2 for the second quarter, and so forth. For example, a quarter is often shown with its relevant year, as in Q1 2021 or Q121, which represents the first quarter of the year 2021.
="Q" &INT((MONTH(A2)+2)/3) We can type this formula into cell B2 and drag the formula down to every remaining cell in column B: The quarter for each date in column A is shown in column B.
To show the quarter as “Q1” or “Qtr 1,” concatenate the appropriate text before the result. In Figure 2, cell A7 uses a formula of =“Q”&ROUNDUP(MONTH(A2)/3,0)&“-”&YEAR(A2) to return “Q1-2017.”
(1) In the Column drop down list, please specify the date column that you will sort by quarter. (2) Click the Sort On drop down list, and select Quarter. (3) Specify the sort order in the Order drop down list.
You need to explicilty Vectorize
your function:
fun_v <- Vectorize(fun, "x") fun_v(Data$date) #[1] "01/01" "01/01" "01/01" "01/02" "01/02" "01/02"
However, when it comes to more or less standard tasks (such as datetime manipulations), there's always a solution already available:
library(zoo) yq <- as.yearqtr(Data$date, format = "%Y-%m-%d") yq #[1] "2001 Q1" "2001 Q1" "2001 Q1" "2001 Q2" "2001 Q2" "2001 Q2"
To convert to your specific format, use
format(yq, format = "%y/0%q") #[1] "01/01" "01/01" "01/01" "01/02" "01/02" "01/02"
I have been loving the lubridate
package for working with dates. Super slick. The quarter
function finds the quarter (of course) and then just pair that with the year.
library(lubridate) Data <- Data %>% mutate(qtr = paste0(substring(year(date),3,4),"/0",quarter(date)))
If you are not familiar with the %>%
from magrittr
the first line basically says "use data frame called Data
" and the second line says "mutate (or add) a column called qtr
"
EDIT 2021-Q2
If the "YY/QQ" format is not critical, then a quick and safe way to get the year and the quarter is:
library(lubridate) Data %>% mutate(qtr = quarter(date, with_year = T))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With