Tung Linh
Tung Linh

Reputation: 321

How to print a list of output as 1 line in R

As part of my an exercise, I am supposed to write a function that replaces the seq() command in R.

I have managed to make one that works similarly:

seq2 <- function(a,r,n){  #a is the starting number, r is the increment, n is the length out
 i <- a
 k <- 1
 repeat{
   print(i)
   i<-i+r
   k=k+1
   if(k>n)
     break
  }
}

However, the output is not really what I want. For example, when calling the seq() command like this:

seq(10,by=5,lenght.out=15)

the output is

 [1] 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80

whereas my code has this output:

seq2(10,5,15)
[1] 10
[1] 15
[1] 20
[1] 25
[1] 30
[1] 35
[1] 40
[1] 45
[1] 50
[1] 55
[1] 60
[1] 65
[1] 70
[1] 75
[1] 80

So is there a way to adjust my code so that it produces the same output as the seq() command?

Thanks

Upvotes: 0

Views: 612

Answers (1)

xraynaud
xraynaud

Reputation: 2126

You can create a new vector within the function and return that vector at the end:

seq2 <- function(a,r,n){  #a is the starting number, r is the increment, n is the length out
  i <- a
  k <- 1
  out = c()
  repeat{
    out = c(out,i)
    i<-i+r
    k=k+1
    if(k>n)
      break
 }
 return(out)
}

Upvotes: 1

Related Questions