In: Statistics and Probability
Given a vector of numeric values. with a R function using loop. testdouble(data). that returns TRUE if all the even indexs elements of the vector are twice their preceding value, other wise your function returns FALSE. You can assume that the given vector has an even number of values.
TRUE scenarios:
c(3, 6, 5, 10, 11, 22, 13, 26)
c(0, 0,1, 2, 2, 4, 3, 6)
FALSE scenarios:
c(3, 7, 5, 6, 11, 22, 13, 26)
c(0, 2, 1, 2, 2, 4, 3, 6)
Now, without using any loop, write your own R function, testdouble2(data), taht returns TRUE, if all the even index elements of the vector are twice their preceding value, otherwise your function returns FALSE.
The R codes fopr two functions with loop and without loop are given below:
#data <- c(3, 6, 5, 10, 11, 22, 13, 26)
#data <-c(0, 0,1, 2, 2, 4, 3, 6)
data <-c(3, 7, 5, 6, 11, 22, 13, 26)
#data <- c(3, 6, 5, 10, 11, 22, 13, 26)
#data <-c(0, 0,1, 2, 2, 4, 3, 6)
testdouble <- function(data)
{
n <- 0:((length(data)/2)-1)
n <- 2*n+1
for(i in n)
{
if (data [i+1] != 2*data[i])
{
return (FALSE)
}
}
return (TRUE)
}
testdouble2 <- function(data)
{
n <- 1:(length(data)/2)
vec <- data[2*n] == 2*data[2*n-1]
if (length(which(vec == FALSE))>0)
{
return (FALSE)
}
return (TRUE)
}
testdouble2(data)
testdouble(data)
Sample output:
> > testdouble2(data) [1] FALSE > testdouble(data) [1] FALSE
No checking is done for the argument length. Even number of array length >= 2 is assumed.
If you want checking whether the data length is even and greater tha 0, add additional code.