H. berg
H. berg

Reputation: 553

R function select value in vector via input value and between values other vector

I am not sure if I explain this correctly... but I have a function with 3 vectors and a value input, where the value of vector 3 (val_3) needs to be selected based on the input value which is between the values in vector 1 (val_1) and 2 (val_2)... How do I do this?

val <- 235412
  
select <- function(val){
  
  val_1 <- c(1, 10, 100, 10000, 100000)
  val_2 <- c(10, 100, 10000, 100000, 1000000)
  val_3 <- c(2:6)
  
  for (i in length(val_1)) {
    
    if (val > val_1[i] && val < val_2[i]){
      select_var = val_3[i]
    }
  }
}

Upvotes: 0

Views: 51

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

Assuming your example is over-simplified and the vectors involved aren't always powers of 10, you can avoid a loop altogether by using the fact that R is vectorized:

select <- function(val) {
  
  val_1 <- c(1, 10, 100, 10000, 100000)
  val_2 <- c(10, 100, 10000, 100000, 1000000)
  val_3 <- c(2:6)
  
  val_3[which(val_1 < val & val_2 > val)]
  
}

select(235412)
#> [1] 6

If your variables inside the function never change, you could even shorten the function to:

select <- function(val) (2:6)[tail(which(log(val, 10) > (0:6)[-4]), 1)]

select(235412)
#> [1] 6

But this is difficult to read and hence would be difficult to debug.

As a side-note here, it would be best not to call your function select, as there are already commonly used functions called select that this would over-write.

Upvotes: 1

Related Questions