How to Find Higher or Lower Values between Columns within a Data Frame in R

Asked

Viewed 208 times

2

I have a data frame x, and in the column of the name V_de_Busca, where the value is greater than 0, I need to search the column V_Encontrado and locate the first value larger than the one searched by following the indexes.

Thus, for example, the value "12" would have to return "14" and not "15", because it is in a date earlier than the value "12" sought. Another example the value "17" would have to return the value of "20", or the value "10" would have to return "12".

x = data.frame(Índice = c(1,2,3,4,5,6,7,8,9,10),
               Data = as.Date(c("2019-01-22", "2019-01-21", "2019-01-20", "2019-01-18", "2019-01-17", "2019-01-16", "2019-01-15", "2019-01-14", "2019-01-11", "2019-01-10")),
               V_Encontrado = c(10,15,18,14,09,06,12,13,20,22), 
               V_de_Busca = c(0,0,0,12,0,10,0,17,07,0))

1 answer

1


The following code calculates for each value of V_de_Busca the first value of V_Encontrado greater than this value of V_de_Busca.

x$Maior <- sapply(seq.int(nrow(x)), function(i){
  if(x[i, "V_de_Busca"] == 0){
    0
  } else {
    j <- i + which(x[i:nrow(x), "V_Encontrado"] > x[i, "V_de_Busca"]) - 1
    if(length(j) > 0) x[j[1], "V_Encontrado"] else 0
  }
})

x
#   Índice       Data V_Encontrado V_de_Busca Maior
#1       1 2019-01-22           10          0     0
#2       2 2019-01-21           15          0     0
#3       3 2019-01-20           18          0     0
#4       4 2019-01-18           14         12    14
#5       5 2019-01-17            9          0     0
#6       6 2019-01-16            6         10    12
#7       7 2019-01-15           12          0     0
#8       8 2019-01-14           13         17    20
#9       9 2019-01-11           20          7    20
#10     10 2019-01-10           22          0     0
  • Perfect, thank you very much. Solved everything you needed.

Browser other questions tagged

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