Home > database >  Setting the range of acceptable input for a vector
Setting the range of acceptable input for a vector

Time:03-30

Let's say I have a numeric vector that specifies acceptable range for an input is 1:4.

In the EXamples below, how can I obtain my desired_output?

acceptable = 1:4

# EX 1:
input = 0:7

desired_output = 1:4


# EX 2:
input = 6
desired_output = 4

CodePudding user response:

We can create a function

f1 <- function(inp, accept) {
    out <- intersect(inp, accept)
    if(length(out) == 0) out <- max(accept)
   return(out)
}

-testing

> input <- 6
> f1(input, acceptable)
[1] 4
> input = 0:7
> f1(input, acceptable)
[1] 1 2 3 4
  • Related