To print value of the next leap year using variable in R programming

Viewed 2498

Question in R basic hands-on,

  1. Create a variable L, and assign the value of the year (2018) to it.

  2. Create another variable NL, assign the value of the next leap year using variable L, and then print NL."

I have tried as below, But am not getting the desired output, Please help me

L <- as.Date("2018")
NL <- L + timedelta(year=4)
print(NL)
3 Answers

This might help :

get_next_leap_year <- function(L) {
   all_years <- L + 1:4
   all_years[(all_years %% 4 == 0 & all_years %%100 != 0) | all_years %% 400 == 0]
}

get_next_leap_year(2018)
#[1] 2020

If you are allowed to use a package you can use leap_year from lubridate.

get_next_leap_year <- function(L) {
   all_years <- L + 1:4
   all_years[lubridate::leap_year(all_years)]
}

It's simple.

Define a (l) var:

l <- 2018

Define a function with the intervale and multiples of leap years:

ny <- function (l){
x <- l + 1:4
x[(x %% 4 == 0 & x %%100 != 0) | x %% 400 == 0] return(x)}

Define a var called nl with function of (l):

nl <- ny(l)

But if you are doing this for FrescoPlay, they just want:

It's simple.

Define a L var:

l <- 2018

Define a function with the intervale and multiples of leap years:

ny <- function (l){
x <- l + 1:4
x[(x %% 4 == 0 & x %%100 != 0) | x %% 400 == 0] return(x)}

Define a var called ND with function of (L):

nl <- ny(l)

But, if you are doing this for FrescoPlay, they just want:

l<- 2018
nl<l+2
nl

You can try this function for various year values which are perfect to test the function:

+------+----------------+
| Year | Next Leap Year |
+------+----------------+
| 1995 |     1996       |
| 1996 |     2004       |
| 1997 |     2004       |
+------|----------------+

L <- as.Date("2005-01-01")

year <- as.numeric(substr(L, start = 1, stop = 4))

NL <- ifelse(test = year %% 400 != 0,
             yes = ifelse(test = (year %% 4 == 0 | year %% 100 == 0),
                          yes = ifelse(test = (year + 4) %% 400 != 0,
                                       yes = year + 4,
                                       no = year + 8 + year %% 4),
                          no = ifelse(test = (year + 4 - year %% 4) %% 400 != 0,
                                      yes = year + 4 - year %% 4,
                                      no = year + 8 - year %% 4)),
             no = year + 4)

NL

Related