Home > Blockchain >  Return TRUE/FALSE if range is within list of ranges R
Return TRUE/FALSE if range is within list of ranges R

Time:09-08

I have a range of numbers

rg <- 25:46

I need to check whether any numbers from that range falls within a string of ranges and return true/false

lrg <- "1:26,48:56,78:99,121:143,165:204,226:243,265:268,290:316"

What i have tried is

for (i in str_split(lrg,',')){ print(noquote(i) %in% rg)}

but this always returns FALSE probably something simple im missing here

CodePudding user response:

Here is a base R solution.

rg <- 25:46
lrg <- "1:26,48:56,78:99,121:143,165:204,226:243,265:268,290:316"

l <- lapply(strsplit(lrg, ",")[[1]], \(x) eval(parse(text=x)))
sapply(l, \(x) any(rg %in% x))
#> [1]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

Created on 2022-09-07 by the reprex package (v2.0.1)

Beware though,

fortunes::fortune(106)
#> 
#> If the answer is parse() you should usually rethink the question.
#>    -- Thomas Lumley
#>       R-help (February 2005)

Created on 2022-09-07 by the reprex package (v2.0.1)

How can a string like lrg be part of a real life question or problem?


Edit

Inspired in yuk's answer and r2evans' comment. In fact, my code above rewritten as a pipe.

strsplit(lrg, ",") |>
  unlist() |>
  lapply(\(x) parse(text = x) |> eval()) |>
  sapply(\(x) any(rg %in% x))
#> [1]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

Created on 2022-09-07 by the reprex package (v2.0.1)

CodePudding user response:

Try this:

rg <- 25:46
lrg <- "1:26,48:56,78:99,121:143,165:204,226:243,265:268,290:316"
l = str_split(lrg, ",", simplify = T) %>% 
  lapply(., function(x) parse(text = x) %>% eval()) %>% 
  unlist()
any(rg %in% l)

CodePudding user response:

Base R using findIntervals:

!all(!findInterval(rg, c(ints <- as.numeric(strsplit(lrg, "\\,|:")[[1]]), ints[length(ints)])) %% 2)

This will work if the ranges are non-overlapping.

  • Related