In: Computer Science
In R studio Write a function that takes as an input a positive integer and uses the print() function to print out all the numbers less than the input integer. (Example: for input 5, the function should print the numbers 1,2,3,4 { for input 1, the function should not print a number.) Use the lapply function, do not use any of the loop commands in your code.
lapply() function takes two parameters. One is a list or a sequence or a vector. The 2nd parameter is a function.
Here we used sequence from 1 to n-1.
We used the condition if(n!=1) because we dont need any o/p when n==1.
Code:
new.function <- function(n) {
if(n != 1){
lapply(seq(1,n-1), print)
}
}
new.function(6)
sample O/P when 6 is passed to function:
> new.function(6)
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] 4
[[5]]
[1] 5
Code and O/P screenshot: