我想知道A[even number]
的计数大于A[even number-1]
>A
[1] 1 2 3 1 4 5 5 6 7
我下面的代码不起作用:
for (i in 1:length(A)){
coun<-0
if (length(A)%%2!=0){
len <- length(A)-1
for (i in 1: len){
if (A[i+1]>A[len]){
coun<-coun+1
}
}
else if (A[i+1]>A[i]){
coun<-coun+1
}
}
在A中,计数应为3,因为(A[2]>A[1],A[4]<A[3],A[6]>A[5],A[8]>A[7],A[9]将不被视为后面没有值(
两种方法:
## find the even indices and
## calculate the differences you want
even_ind = seq_along(A)[c(F, T)]
sum(A[even_ind] > A[even_ind - 1])
# [1] 3
## or, calculate all differences,
## and take every other one
sum((diff(A) > 0)[c(T, F)])
# [1] 3