Need to fix a problem with seq function in R

I have to create a function with 2 arguments (a,b) that will return the first n multiples of 3 that are less than or equal to a. Here is what i am doing:


 f <- function(a, b){
  
    v = seq(from = 0, to= a, by = 3, length.out = b)
    return(v)

}

It says that the seq() has too many arguments, and I understand why. If i remove the 'from', there would be some cases where the vector wouldnt started with zero. How could i fix the problem?

THank you

Upvotes: 0

Views: 249

Answers (2)

MichaelChirico
MichaelChirico

Reputation: 34763

How about the following?

f <- function(a, b) {
  if (3 * b > a) return(seq(0L, a, by = 3L))
  return(seq(0, by = 3L, length.out = b))
}

Upvotes: 0

r2evans
r2evans

Reputation: 161110

seq supports either by= or length.out=, not both. You can have the same affect with head(seq(...)):

seq(from = 0, to = 20, by = 3, length.out = 4)
# Error in seq.default(from = 0, to = 20, by = 3, length.out = 4) : 
#   too many arguments
seq(from = 0, to = 20, by = 3)
# [1]  0  3  6  9 12 15 18
head(seq(from = 0, to = 20, by = 3), n = 4)
# [1] 0 3 6 9

which for your function should be:

f <- function(a, b){
    head(seq(from = 0, to = a, by = 3), n = b)
}
f(20, 4)
# [1] 0 3 6 9

Upvotes: 1

Related Questions