Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an R function or loop that will print every third number or nth number in [1, 100]?

Tags:

r

I am trying to write a function in R which will print every 3rd number in [1,100]; this is what I have tried, but this doesn't produce every third number, it produces every number

x <- c(100)
question.1 <- function (x){
out <- seq(x)
 return(out)
}
question.1(x)

Am I missing something? Any help you can offer would be greatly appreciated!

like image 755
Noz Avatar asked Jul 25 '15 02:07

Noz


1 Answers

Use the modulo operator (%%) to obtain every nth value from 1:100 like this:

nth <- function(x,n){
  x[x%%n==0]
}

For example:

x <- 1:100
nth(x,7)
[1]  7 14 21 28 35 42 49 56 63 70 77 84 91 98
like image 52
R. Schifini Avatar answered Dec 22 '22 17:12

R. Schifini