d1 <- "2/11/1962"
d1[1] "2/11/1962"
Dr. Peng Zhao (✉ peng.zhao@xjtlu.edu.cn)
Department of Health and Environmental Sciences
Xi’an Jiaotong-Liverpool University
Character:
d1 <- "2/11/1962"
d1[1] "2/11/1962"
d1 + 1Advantages:
Disadvantages:
Numeric:
Advantages:
Disadvantages:
Date/time format:
d2 <- Sys.Date()
d2[1] "2023-03-02"
t2 <- Sys.time()
t2[1] "2023-03-02 11:22:59 CST"
d2 + 1[1] "2023-03-03"
t2 + 1[1] "2023-03-02 11:23:00 CST"
class(d2)[1] "Date"
class(t2)[1] "POSIXct" "POSIXt"
Paired functions: as.Date() and format().
d3 <- as.Date("2/11/1962", format="%d/%m/%Y" )
as.numeric(d3)
d3 + 2617
d4 <- as.Date( "2/11/1962", format="%m/%d/%Y" )
format(d3, '%Y %m %d')
format(d3, "%A %d %B %Y")library('Epi')
data("diet")
help(diet)
str(diet)
bdat <- diet$dox[1]
format(bdat, format="%A %d %B %Y")
diet$dox2 <- format(diet$dox, format="%A %d %B %Y")
bdat + 1
max(diet$dox)
range(diet$dox)
mean(diet$dox)
median(diet$dox)
diff(range(diet$dox))
difftime(min(diet$dox), max(diet$dox), units = "weeks")
Epi::cal.yr(bdat)
diet2 <- Epi::cal.yr(diet)
str(diet2)Universal functions: strptime() and format():
bd <- '1994-09-22 20:30:00'
class(bd)
bdtime <- strptime(x = bd, format = '%Y-%m-%d %H:%M:%S', tz = "Asia/Shanghai")
class(bdtime)
bdtime$wday
unclass(bdtime)
format(bdtime, format = '%d.%m.%Y')Other functions:
date()
Sys.Date()
Sys.time()bdtime + 1
bdtime2 <- strptime(
'1995-09-01 7:30', format = '%Y-%m-%d %H:%M',
tz = 'Asia/Shanghai')
bdtime2 - bdtime
difftime(time1 = bdtime2, time2 = bdtime, units = 'secs')
mean(c(bdtime, bdtime2))Which day of the year is it?
Convert it as “Year, Month in English and Date, Weekday in English”, such as “2023, January 1, Sunday”.
Suppose we get to know each other at 15:00, September 13, 2022. How many days have we known each other until now? How many hours? How many seconds?
The anniversary is September 13, 2023. What day is it? How about in 2024? Plot a graph for September 13 of each year, with the weekday as x and the year as y.
Create a new column “Date”, showing the date in the format of “Year-month-day”, such as “2023-01-31”.
Plot a graph for each atmospheric variable (i.e. ozone in ppb, solar radiation in W m-2, wind speed in m s-1, air temperature in °C) against the date.
Create a new column “Weekday”, showing the day in the week (1 as Monday and 7 as Sunday).
Calculate the mean values of each atmospheric variable for each weekday.
Plot a graph for each atmospheric variable with the mean values against the weekdays.