Convert data type from character to date.

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

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:

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:

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:

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:

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

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

答案1

得分: 1

以下是您要翻译的内容:

我在编程方面不是最擅长的,但这将是我的解决方案。

    df <- data.frame(title = c("this is a title",
                               "this is another title"),
                     date = c("2022:02:15 0231",
                              "2022:10:06 0800"))
    
    df2 <- df %>%
      mutate(date = as.Date(gsub(":", "-", str_sub(date, 1, 10))))

    class(df2$date)
我是通过以下方式解决的:

    a <- "2022:02:15 0231"
    a
    
    b <- str_sub(a, 1, 10)
    b
    
    c <- gsub(":", "-", b)
    c
    
    d <- as.Date(c)
    d
英文:

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

df &lt;- data.frame(title = c(&quot;this is a title&quot;,
                           &quot;this is another title&quot;),
                 date = c(&quot;2022:02:15 0231&quot;,
                          &quot;2022:10:06 0800&quot;))

df2 &lt;- df %&gt;% 
  mutate(date = as.Date(gsub(&quot;:&quot;, &quot;-&quot;, str_sub(date, 1, 10))))

class(df2$date)

I worked it through the following way:

a &lt;- &quot;2022:02:15 0231&quot;
a

b &lt;- str_sub(a, 1, 10)
b

c &lt;- gsub(&quot;:&quot;, &quot;-&quot;, b)
c

d &lt;- as.Date(c)
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:

确定