[英]Transform chr to date format in R
I want to transform from chr to date format I have this representing year -week: 2020-53 I ve tried to do this我想从 chr 转换为日期格式我有这个代表年 - 周:2020-53 我试过这样做
mutate(semana=as_date(year_week,format="%Y-%U"))
but I get the same date in all dataset 2020-01-18但我在所有数据集中得到相同的日期 2020-01-18
I also tried我也试过
mutate(semana=strptime(year_week, "%Y-%U"))
getting the same result Here you can see the wrong convertion得到相同的结果在这里你可以看到错误的转换 Any idea?, thanks有什么想法吗,谢谢
I think I've got something that does the job.我想我有一些东西可以完成这项工作。
library(tidyverse)
library(lubridate)
# Set up table like example in post
trybble <- tibble(year_week = c("2020-53", rep("2021-01", 5)),
country = c("UK", "FR", "GER", "ITA", "SPA", "UK"))
# Function to go into mutate with given info of year and week
y_wsetter <- function(fixme, yeargoal, weekgoal) {
lubridate::year(fixme) <- yeargoal
lubridate::week(fixme) <- weekgoal
return(fixme)
}
# Making a random date so col gets set right
rando <- make_datetime(year = 2021, month = 1, day = 1)
# Show time
trybble <- trybble %>%
add_column(semana = rando) %>% # Set up col of dates to fix
mutate(yerr = substr(year_week, 1, 4)) %>% # Get year as chr
mutate(week = substr(year_week, 6, 7)) %>% # Get week as chr
mutate(semana2 = y_wsetter(semana,
as.numeric(yerr),
as.numeric(week))) %>% # fixed dates
select(-c(yerr, week, semana))
Notes:笔记:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.