Home > Mobile >  Zero position matters: one selection problem
Zero position matters: one selection problem

Time:05-10

I'd like to match some results by a rule. In my case:

original.names <- c("TL-13","TL-09","TL-12","TL-19A","TL-11","TL-20","TL-16",
"TL-15","TL-14","TL-10","TL-18","TL-19","TL-08A","TL-07A","TL-17A","TL-17",
"TL-21","TL-09A","TL-22","TL-08","TL-05","TL-03","TL-06","TL-07","TL-02","TL-04","TL-01") 

selection <- c(1)

which(original.names==selection)
#integer(0)

But in my case TL-01 is 1. If I make which(gsub("TL-|0","",original.names)==selection), it doesn't work too because 10 and 01 are different and gsub turns equal. Sometimes I have something like 8A (number-alphabetic) and I need to consider this situation too.

Please any help with it?

CodePudding user response:

Similar approach to @benson23 but capturing the required value instead of removing.

which(as.integer(sub('TL-(\\d ).*', '\\1', original.names)) == selection)
#[1] 27

This captures the numbers that occurs after TL-, converts it to integer and compares it with selection.

CodePudding user response:

You'll need to remove all character strings from your original.names, then convert it to integer type before you can do a comparison.

original.names <- c("TL-13","TL-09","TL-12","TL-19A","TL-11","TL-20","TL-16",
                    "TL-15","TL-14","TL-10","TL-18","TL-19","TL-08A","TL-07A","TL-17A","TL-17",
                    "TL-21","TL-09A","TL-22","TL-08","TL-05","TL-03","TL-06","TL-07","TL-02","TL-04","TL-01") 

selection <- 1

which(as.integer(gsub("\\D", "", original.names)) == selection)
[1] 27

CodePudding user response:

Here's another option using parse_number, although we have to wrap with abs as readr will take the dash to be a negative.

library(readr)

which(abs(parse_number(original.names)) == selection)

# [1] 27

CodePudding user response:

We could use str_pad:

library(stringr)

which(str_match(original.names, '\\d ')== 
        str_pad(selection, 2, pad = "0"))

[1] 27

CodePudding user response:

You can remove everything before - and also the following 0.

selection <- 1
which(sub("^.*-0*", "", original.names) %in% sub("^0*", "", selection))
#[1] 27

selection <- "8A"
which(sub("^.*-0*", "", original.names) %in% sub("^0*", "", selection))
#[1] 13

selection <- "01"
which(sub("^.*-0*", "", original.names) %in% sub("^0*", "", selection))
#[1] 27

selection <- c(1, "8A")
which(sub("^.*-0*", "", original.names) %in% sub("^0*", "", selection))
#[1] 13 27
  • Related