简体   繁体   中英

How to print function's output as a vector?

I have to create a function called vast that prints leap years between year1 and year2 as a vector.

So this is the code I have been using:

vast <- function(year1,year2) {
  year <- year1
  for(year in year1:year2) {
    if(((year%%4==0)&(year%%100!= 0))|(year%%400==0))
    vast <- print(year)
  }
}

When I use vast(2000,2010), it should give (2000,2004,2008) as a vector that can be saved into x, but instead I get:

x <- vast(2000,2010)
[1] 2000
[1] 2004
[1] 2008
x
NULL

So the x is empty. I feel so stupid but I just can't figure it out.

You need to return the values at the end of the function. You can explicitly use return to do that or the last line in the function is automatically returned.

Also comparison operators are vectorised so you can do

vast <- function(year1,year2){
  year <- year1 : year2
  leap_year <- year[(year %%4 == 0 & year %% 100 != 0) | (year %% 400 == 0)]
  return(leap_year)
}

then call vast

x <- vast(2000,2010)
x
#[1] 2000 2004 2008

You can add a print(leap_year) statement in the function if you want to print the years.

You have to use the return() function if you want to have the value out of the function. Here is possible solution for your code:

vast <- function(year1,year2){
  vast <- c()
  year <- year1
  for(year in year1:year2){
    if(((year%%4==0)&(year%%100!= 0))|(year%%400==0)){
      vast <- c(vast, year)
    }
  }
  return(vast)
}

x <- vast(2000,2010)
x

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM