How to create a list of values with restriction on a stipulated number of data

Asked

Viewed 47 times

2

I have the following code

n <- 130  
pl <- trunc(n/20)
p0 <- 20
pp <- 20 + (0:(pl-1))*p0 

With the result of pp, being: [1] 20 40 60 80 100 120. In addition, I also use the same process for creating a pe, according to the following code:

pe <- c(1:8)
for(i in 1:6){
  pe[i] <- pl*20+i*20}
pe[7] <- pe[6]+100
pe[8] <- pe[7]+100

Likewise, the result of peis: [1] 140 160 180 200 220 240 340 440.

The above codes are used to calculate values that will be considered to determine the amount of observations extracted from a data file that has 485 observations. However, I have another file that has only 199 original observations and I need to create a looping that creates this list, but with the following restrictions: The resulting values of pe should not exceed the amount of observations in the file, defined in my algorithm as: (nrow(dados_original)) and, preferably the variables should contain 5 values with an interval of 20 units between them. In the case of the 199 observations, it would be only (140,160,180). In the case of 350 observations it would be (140,160,180,200,220,320). Thank you for the suggestions.

  • It says that the variables should contain 5 values but in the case of 350 observations (140,160,180,200,220,320) has 6 values. It is a mistake?

1 answer

3

See if the following function is what you want. The results are in line with the expected results of the question.

valores <- function(obs, n = 130, incr = 20, incr2 = 100, comprimento = 5){
  pl <- trunc(n/incr)
  res <- seq(pl*incr + incr, obs, by = incr)
  if(length(res) > comprimento){
    res <- res[seq_len(comprimento)]
    res <- c(res, seq(res[comprimento] + incr2, obs, by = incr2))
  }
  res
}

valores(199)
#[1] 140 160 180

valores(350)
#[1] 140 160 180 200 220 320
  • Its function presents an error for values between 240 and 310. Some files have observations between these values. Some problem with incr2 I think.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.