Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple string replacement, decimals to quarters

I want to replace .00 with -Q1, .25 with -Q2, .50 with -Q3, and .75 with -Q4 as given below. However, my code is not working as expected. Any hints?

library(tidyverse)

dt1 <- 
  tibble(Date = c(2015.00, 2015.25, 2015.50, 2015.75))

dt1
# A tibble: 4 x 1
   Date
  <dbl>
1 2015 
2 2015.
3 2016.
4 2016.

dt1 %>% 
  pull(Date)

[1] 2015.00 2015.25 2015.50 2015.75

dt1 %>% 
  mutate(Date1 = str_replace_all(string = Date, pattern = c(".00" = "-Q1", ".25" = "-Q2", ".50" = "-Q3", ".75" = "-Q4")))

# A tidytable: 4 × 2
   Date Date1  
  <dbl> <chr>  
1 2015  2015   
2 2015. 2015-Q2
3 2016. 2015.5 
4 2016. 2015-Q4
like image 285
MYaseen208 Avatar asked Aug 15 '26 21:08

MYaseen208


2 Answers

There also is a zoo-function for that:

library(tidyverse)
library(zoo)

dt1 <- 
  tibble(Date = c(2015.00, 2015.25, 2015.50, 2015.75))

dt1 %>%
  mutate(Date1 = format.yearqtr(Date, format = "%Y.Q%q") )

# Date Date1  
# <dbl> <chr>  
# 1 2015  2015.Q1
# 2 2015. 2015.Q2
# 3 2016. 2015.Q3
# 4 2016. 2015.Q4
like image 161
r.user.05apr Avatar answered Aug 18 '26 12:08

r.user.05apr


You may also use integer division %/% and modulo division %% simultaneously

paste0(dt1$Date %/% 1, '-Q',(dt1$Date %% 1)*4 +1)

[1] "2015-Q1" "2015-Q2" "2015-Q3" "2015-Q4"

Thus, using it in piped syntax as

dt1 %>%
  mutate(date1 = paste0(Date %/% 1, '-Q',(Date %% 1)*4 +1))

# A tibble: 4 x 2
   Date date1  
  <dbl> <chr>  
1 2015  2015-Q1
2 2015. 2015-Q2
3 2016. 2015-Q3
4 2016. 2015-Q4
like image 38
AnilGoyal Avatar answered Aug 18 '26 12:08

AnilGoyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!