Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R/ Shiny - How to get current year with Sys.Date()?

Tags:

r

shiny

How can I get current year with Sys.Date()?

I have this code below,

      selectInput(
        inputId = "year",
        label = "Year:",
        choices = c(2014:Sys.Date())
        )

result,

<select id="year"><option value="2014" selected>2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
....
<option value="16582">16582</option></select>

But I just need,

<select id="year">
    <option value="2014" selected>2014</option>
    <option value="2015">2015</option>
</select>

Any ideas?

like image 704
Run Avatar asked May 27 '15 03:05

Run


People also ask

How do I get the current year in R?

To get the year from a date in R you can use the functions as. POSIXct() and format() . For example, here's how to extract the year from a date: 1) date <- as. POSIXct("02/03/2014 10:41:00", format = "%m/%d/%Y %H:%M:%S) , and 2) format(date, format="%Y") .

How do I extract the year from a date in R?

In this method, the as. POSIXct is a Date-time Conversion Functions that is used to manipulate objects of classes. To extract the year from vector we need to create a vector with some dates and then arrange the date with as. POSIXct() and get year with format() methods.

What is the class of SYS date () and SYS time ()?

Sys. time returns an object of class "POSIXct" (see DateTimeClasses). On almost all systems it will have sub-second accuracy, possibly microseconds or better. On Windows it increments in clock ticks (usually 1/60 of a second) reported to millisecond accuracy.

What is the function used to find current date in R?

date() function in R Language is used to return the current date and time.


Video Answer


2 Answers

You can just use the format() function here as outlined in the help page for Sys.Date(). See ?strptime for all the different specifications:

> c(2014, format(Sys.Date(), "%Y"))
[1] "2014" "2015"

If you actually need integer values, then:

> c(2014L, as.integer(format(Sys.Date(), "%Y")))
[1] 2014 2015
like image 89
Chase Avatar answered Sep 19 '22 09:09

Chase


Couldn't you just do this:

choices = c(2014:lubridate::year(Sys.Date()))

using lubridate to get the year from Sys.Date()?

like image 20
jalapic Avatar answered Sep 18 '22 09:09

jalapic