简体   繁体   English

将日期更改为该月的最后一天

[英]change date to the last day of the month

I've tried to change the character variable into a variable of class Date, then changed it to the last day of the month.我尝试将字符变量更改为 class 日期的变量,然后将其更改为该月的最后一天。

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这在通过控制台运行时有效,但是当我尝试编织到 pdf 时,我得到了

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. days_in_month(data$Month) 中的错误:找不到 function "days_in_month" 调用:... withCallingHandlers -> withVisible -> eval -> eval -> paste 另外:警告消息:在 has_crop_tools() 中:Tool(s) not在 PATH 中安装与否:ghostcript -> 因此,图形裁剪将被禁用。 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?我想保留 as.Date 和 days_in_month() 但我不确定我做错了什么,是否可以将第二行代码加入第一行?

Try adding:尝试添加:

library(lubridate)

in some chunk before that command.在该命令之前的某个块中。 It should work.它应该工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM