Write an R function named fifth with a single vector argument x that calculates and returns the sample mean of he 5th, 10th, 15th, ... elements of x. You may assume that x has at least 5 elements.
The following code gives you the required functionality:
myFunction <- function(x)
{
i <- 1
j <- 1
y <- vector()
while(i<=length(x))
{
if( i %% 5 == 0)
{
y[j] <-
x[i]
j = j + 1
}
i = i + 1
}
res <- mean(y)
return (res)
}
x <-
c(1,2,3,4,5,6,7,8,9,3,5,45,6,43,3,3,43,23,23,43,23,23,32)
ans <- myFunction(x)
print(ans)
Output:
[1] 13.5
Code's link:
http://ideone.com/qZeVyX
Get Answers For Free
Most questions answered within 1 hours.