This is the first line of my dataframe (with column names):
site, date, value
TEES, 20000314, 315
As you can see, the dates don't have separators (- or /), so I can't use as.Date
. Thus, I need something like this:
TEES, 2000-03-14, 315
How do I do this? Presumably something with sub
Will this work:
as.Date(gsub('(\\d{4})(\\d{2})(\\d{2})','\\1-\\2-\\3',df$date))
[1] "2000-03-14"
Data:
df
site date value
1 TEES 20000314 315
You could use the ymd
function from the lubridate
package. This will automatically add "-" to separate YYYY-MM-DD and convert it to Date
.
library(lubridate)
ymd(df$date)
# "2000-03-14"
You can use as.Date
you just need to specify the tryFormats
argument:
as.Date("20000314", tryFormats = c("%Y%m%d"))
[1] "2000-03-14"
The default is to try these formats: c("%Y-%m-%d", "%Y/%m/%d")
, which don't match your current structure so you have to tell it how to read your structure.
We can use anydate
from anytime
library(anytime)
anydate("20000314")
#[1] "2000-03-14"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.