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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With