英文:
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 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?
答案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 <- 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)
I worked it through the following way:
a <- "2022:02:15 0231"
a
b <- str_sub(a, 1, 10)
b
c <- gsub(":", "-", b)
c
d <- as.Date(c)
d
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论