In: Computer Science
In R: write a function that inputs a vector x and a number n and returns the first n elements of x. When n is greater than length(x), your function should just return x.
We are not allowed to use any control flow statements
Please find below R code and Screenshot and dont forget to give a Like.
Code without comments:
vec<-c(5,6,7,8,9,10,11)
func<-function(vec){
n<-5
if(length(vec)<n){
result<-vec
}
else{
result<-vec[0:n]
}
return(result)
}
print(func(vec))
Code with comments:
#creating a vector with elements
vec<-c(5,6,7,8,9,10,11)
#creating a function called func that take a vector as
parameter
func<-function(vec){
n<-5
#if the length of vector is less than n it will display all the
element in r
if(length(vec)<n){
#assigning all the values to the result
result<-vec
}
else{
#vector slicing for first n elements
result<-vec[0:n]
}
#returning the result
return(result)
}
#printing the result
print(func(vec))
Output 1: For given N value, the function displays the first n elements from the vector
Output 2: if size of vector is smaller than N then it displays all the elements in the vector