Dates and Times – Simple and Easy with lubridate exercises (part 1)
转自 R-Excecise 论坛的一篇文章, 针对lubricate包的练习。Dates and Times – Simple and Easy with lubridate exercises (part 1)
Parsing Date-times
The ymd() series of functions are used to parse character strings into dates.
The letters y, m, and d correspond to the year, month, and day elements of a date-time.
Exercise 1
Populate a variable called “start_date” with a date representation of string “23012017”
Exercise 2
Use the lubridate function today to print the current date
Exercise 3
Extract the year part from the “start_date” variable created on exercise 1
Exercise 4
Extract the month part from the “start_date” variable created on exercise 1
Exercise 5
Extract the day part from the “start_date” variable created on exercise 1
Exercise 6
Set the month in variable “start_date” to February
Exercise 7
Add 6 days to variable “start_date”.
Did you notice what happened to the month value?
Exercise 8
Substract 3 months from variable “start_date”
Exercise 9 (Advanced)
Populate a field called concatenated_dates with a vector of dates containing the following values:
“31.12.2015”, “01.01.2016”, “15.02.2016”
Exercise 10 (Advanced)
Calculate in a short and simple way the addition of 1 thru 10 days to “start_date” variable
答案
Below are the solutions to these exercises on dates and times – Simple lubridate Exercises.
##################### ## Exercise 1 ## #####################start_date<- dmy("23012017")start_date
## [1] "2017-01-23"
##################### ## Exercise 2 ## #####################today()
## [1] "2016-08-14"
##################### ## Exercise 3 ## #####################year(start_date)
## [1] 2017
##################### ## Exercise 4 ## #####################month(start_date)
## [1] 1
##################### ## Exercise 5 ## #####################day(start_date)
## [1] 23
##################### ## Exercise 6 ## #####################month(start_date) <- 2##################### ## Exercise 7 ## #####################start_date + days(6)
## [1] "2017-03-01"
##################### ## Exercise 8 ## #####################start_date - months(3)
## [1] "2016-11-23"
##################### ## Exercise 9 ## #####################concatenated_dates <- dmy(c("31.12.2015", "01.01.2016", "15.02.2016"))concatenated_dates
## [1] "2015-12-31" "2016-01-01" "2016-02-15"
##################### ## Exercise 10 ## #####################start_date + c(1:10) * days(1)
## [1] "2017-02-24" "2017-02-25" "2017-02-26" "2017-02-27" "2017-02-28"## [6] "2017-03-01" "2017-03-02" "2017-03-03" "2017-03-04" "2017-03-05"