Home > database >  Find the sum of specific elements from an interval (simulation required)
Find the sum of specific elements from an interval (simulation required)

Time:11-16

I would like to do some simulation with for loop/while loop/ifelse (or any other method) to get the total number of elements from a specific interval. Thank you in advance if you can help me! i've been struggling a lot for this question!

There must have a difference of more than 1 in between the elements of the second set of five numbers and the elements of the first set of five numbers, then also a difference of more than 1 for the elements of the third set of five numbers and elements of second set of five numbers, and so on for the following set of five numbers

Code to get the interval:

set.seed(50) 
a=sort(runif(10,0,1)) 
b=sort(runif(30,1,4)) 
total=c(a,b) 

for example, from the interval in the picture, total[1], total[2], total[3], total[4] and total[5] are my first five numbers, then my next 5 numbers must have a difference of more than one compared with the first 5 numbers. Hence, the next 5 numbers must be total[11], total[12], total[13], total[14], total[15]. then the 11th number must be total[27] because total[27] is the first element that has a difference of more than one compared with total[11].

May I know whether there are any ways to get the sum of the elements of total[1], total[2], total[3], total[4] and total[5], total[11], total[12],...,total[27],....? without counting manually

enter image description here

CodePudding user response:

Here is a solution with an for() loop. First we create a dataframe with needed number of rows and columns. Then, inside the for loop we get a set of five numbers and compare it to the last set. After the for loop we keep only rows of the dataframe which are of interest, e.g. with the sets being a difference of one or more.

n_rows <- length(total)-4
df <- data.frame(ind= rep(NA, n_rows), keep= rep(FALSE, n_rows))
df$ind[1] <- 1; df$keep[1] <- TRUE
last_ind <- 1

for(i in 2:(length(total)-4)){
  set_i <- total[i:(i 4)]
  last_set <- total[last_ind:(last_ind 4)]


  df$ind[i] <- i
  df$keep[i] <- all(set_i - last_set >= 1)
  last_ind <- df$ind[max(which(df$keep))]

}

df <- df[df$keep, ]

df
   ind keep
1    1 TRUE
11  11 TRUE
27  27 TRUE
  • Related