Determine if 3rd digit in string is 0 in R

Viewed 88

Trying to figure out the code to determine if the ( 3rd digit in a string is 0 ) or if the ( 3rd is 5 and the 4th is 6 ) and can't seem to find anything. Feels like a simple thing to do if I wasn't specifically looking for the specific character numbers/digits.

x <- c( "123456" , "124567" , "125600" )

How can I test the above example where the results will be FALSE FALSE TRUE?

Thanks in advance!

6 Answers

We can use sub to capture the 3rd and 4th digits and check if it is equal to 56

sub("^..(..).*", "\\1", x) == 56
#[1] FALSE FALSE  TRUE

Or with substr

substr(x, 3,4) == 56
#[1] FALSE FALSE  TRUE

Alternatively to regex expression, you can use strsplit:

x <- c( "123456" , "124567" , "125600","120156" )

sapply(x,function(v) unlist(strsplit(v,""))[3] ==0)

123456 124567 125600 120156 
 FALSE  FALSE  FALSE   TRUE 

sapply(x,function(v) unlist(strsplit(v,""))[4:5] == c(5,6))
     123456 124567 125600 120156
[1,]  FALSE   TRUE  FALSE  FALSE
[2,]  FALSE   TRUE  FALSE  FALSE

# Or with the correct order:
sapply(x,function(v) paste0(unlist(strsplit(v,""))[3:4],collapse = "") == 56)
123456 124567 125600 120156 
 FALSE  FALSE   TRUE  FALSE 

Test if the 3rd digit is a zero

substr( c( "123456" , "124567" , "125600" , "30000" ) , 3,3) %in% 0

We can use substring to get characters from specific position.

substring(x, 3, 3) == 0 | substring(x, 3, 4) == 56
#[1] FALSE FALSE  TRUE

Just as you have explained it substring(x, 3, 3) == 0 checks if 3rd digit is 0 OR (|) 3rd and 4th digit substring(x, 3, 4) is 56 respectively.

Check if

  • 3rd digit is 0, OR
  • 3rd digit is 5 and 4th is 6
x <- c( "123456" , "124567" , "125600", "120234")

sub("^..((0|56)).*","\\1",x) %in% c(0,56)

# [1] FALSE FALSE  TRUE  TRUE

One way to do it for strings of equal length.

x <- c( "123456" , "124567" , "125600" )
x <- as.data.frame(strsplit(x, ""), stringsAsFactors = FALSE, fix.empty.names = FALSE)
x[3,] %in% 3   # [1]  TRUE FALSE FALSE
x[3,] %in% 0   # [1] FALSE FALSE FALSE
x[4,] %in% 6   # [1] FALSE FALSE  TRUE

strings with unequal length

x <- c( "123456" , "124567" , "1256000" )
x <- strsplit(x, "")
x <- sapply(x, "[", i = seq_len(max(lengths(x))))
x[3,] %in% 3   # [1]  TRUE FALSE FALSE
x[3,] %in% 0   # [1] FALSE FALSE FALSE
x[4,] %in% 6   # [1] FALSE FALSE  TRUE
Related