Convert data type from character to date.

huangapple go评论91阅读模式
英文:

Convert data type from character to date

问题

I am failing to convert a data type chatacter into a date.
This is an example how my data looks like:

title date
this is a title 2022:02:15 0231
this in another title 2022:10:06 0800

I have tried to convert the date, that is at the moment a character type into a date type and remove the last 4 numbers:

  1. df$date <- as.Date(sub("\\s\\d{4}$", "", df$date), format = "%Y:%m:%d", origin = "1970:01:01")

Unfortunately this gives me a double. So I have tried also to do this:

  1. df$date <- as.Date(df$date)

Still getting a double and not a date format.
What do I do wrong?

英文:

I am failing to convert a data type chatacterinto a date.
This is an example how my data looks like:

title date
this is a title 2022:02:15 0231
this in another title 2022:10:06 0800

I have tried to convert the date, that is at the moment a character type into a date type and remove the last 4 numbers:

  1. df$date <- as.Date(sub("\\s\\d{4}$", "", df$date), format = "%Y:%m:%d", origin = "1970:01:01")

Unfortunately this gives me a double. So I have tried also to do this:

  1. df$date <- as.Date(df$date)

Still getting a doubleand not a dateformat.
What do I do wrong?

答案1

得分: 1

以下是您要翻译的内容:

  1. 我在编程方面不是最擅长的,但这将是我的解决方案。
  2. df <- data.frame(title = c("this is a title",
  3. "this is another title"),
  4. date = c("2022:02:15 0231",
  5. "2022:10:06 0800"))
  6. df2 <- df %>%
  7. mutate(date = as.Date(gsub(":", "-", str_sub(date, 1, 10))))
  8. class(df2$date)
  9. 我是通过以下方式解决的:
  10. a <- "2022:02:15 0231"
  11. a
  12. b <- str_sub(a, 1, 10)
  13. b
  14. c <- gsub(":", "-", b)
  15. c
  16. d <- as.Date(c)
  17. d
英文:

I am not the best at coding but this would be my solution.

  1. df &lt;- data.frame(title = c(&quot;this is a title&quot;,
  2. &quot;this is another title&quot;),
  3. date = c(&quot;2022:02:15 0231&quot;,
  4. &quot;2022:10:06 0800&quot;))
  5. df2 &lt;- df %&gt;%
  6. mutate(date = as.Date(gsub(&quot;:&quot;, &quot;-&quot;, str_sub(date, 1, 10))))
  7. class(df2$date)

I worked it through the following way:

  1. a &lt;- &quot;2022:02:15 0231&quot;
  2. a
  3. b &lt;- str_sub(a, 1, 10)
  4. b
  5. c &lt;- gsub(&quot;:&quot;, &quot;-&quot;, b)
  6. c
  7. d &lt;- as.Date(c)
  8. d

huangapple
  • 本文由 发表于 2023年5月17日 18:18:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定