简体   繁体   English

在 R 中将 chr 转换为日期格式

[英]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:笔记:

  • If you somehow plug in a week greater than 53, lubridate doesn't mind, and goes forward a year.如果您以某种方式插入大于 53 的一周,则 lubridate不会介意,并继续前进一年。
  • I really struggled to get mutate to play nicely without writing my own function y_wsetter .在没有编写自己的 function y_wsette的情况下,我真的很难让mutate玩得很好。 In my experience with mutates with multiple inputs, or where I'm changing a "property" of a value instead of the whole value itself, I need to probably write a function.根据我对具有多个输入的变异的经验,或者我正在更改一个值的“属性”而不是整个值本身,我可能需要编写一个 function。 I'm using the lubridate package to change just the year or week based on your year_week column, so this is one such situation where a quick function helps mutate out.我正在使用lubridate package 根据您的year_week列仅更改年份或星期,因此这是一种快速 function 有助于变异的情况。
  • I was having a weird time when I tried setting rando to Sys.Date(), so I manually set it to something using make_datetime .当我尝试将rando设置为 Sys.Date() 时,我遇到了一段奇怪的时间,所以我使用make_datetime手动将其设置为某个值。 YMMV YMMV

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

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