0

I've tried to change the character variable into a variable of class Date, then changed it to the last day of the month.

data %>% mutate("Month"= as.Date(paste(Month,"-01",sep=""))) -> data
data$Month <- paste(format(data$Month, format="%Y-%m"),"-", days_in_month(data$Month), sep="")

This works when run through the console but when I try to knit to pdf I get

Error in days_in_month(data$Month) : could not find function "days_in_month" Calls: ... withCallingHandlers -> withVisible -> eval -> eval -> paste In addition: Warning message: In has_crop_tools() : Tool(s) not installed or not in PATH: ghostcript -> As a result, figure cropping will be disabled. Execution halted

I want to keep as.Date and days_in_month() but I'm not sure what I'm doing wrong and is it possible to join the second line of code to the first line?

2 Answers2

0

Try adding:

library(lubridate)

in some chunk before that command. It should work.

  • Please refer to https://stackoverflow.com/questions/41815365/error-invalid-input-date-trans-works-with-objects-of-class-date-only/41876606 for that – Aru Bhardwaj Apr 11 '21 at 10:31
0
if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse, lubridate)

data <- tribble( ~ id, ~ Month,
                 1, "2020-04",
                 2, "2020-05",
                 3, "2020-12")
data %>%
  mutate(Month = ymd(paste0(Month, "-01")),
         Month = Month + days(days_in_month(Month) - 1))
#> # A tibble: 3 x 2
#>      id Month     
#>   <dbl> <date>    
#> 1     1 2020-04-30
#> 2     2 2020-05-31
#> 3     3 2020-12-31
crestor
  • 1,388
  • 8
  • 21