Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the first 2 Characters in a string

Tags:

r

substr

I need to extract the 1st 2 characters in a string to later create bin plot distribution. vector:

x <- c("75 to 79", "80 to 84", "85 to 89")  

I have gotten this far:

substrRight <- function(x, n){   substr(x, nchar(x)-n, nchar(x)) } 

invoke function

substrRight(x, 1) 

Response

[1] "79" "84" "89" 

Need to prints the last 2 characters not the first.

[1] "75" "80" "85" 
like image 943
Seb Avatar asked Aug 03 '16 17:08

Seb


People also ask

How do you get the first two characters of a string?

Use the String. substring() method to get the first two characters of a string, e.g. const first2 = str. substring(0, 2); . The substring method will return a new string containing the first two characters of the original string.

How do I extract the first 3 characters in R?

To get the first n characters from a string, we can use the built-in substr() function in R. The substr() function takes 3 arguments, the first one is a string, the second is start position, third is end position. Note: The negative values count backward from the last character.

How do you extract the first 5 characters from the string str?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.


1 Answers

You can just use the substr function directly to take the first two characters of each string:

x <- c("75 to 79", "80 to 84", "85 to 89") substr(x, start = 1, stop = 2) # [1] "75" "80" "85" 

You could also write a simple function to do a "reverse" substring, giving the 'start' and 'stop' values assuming the index begins at the end of the string:

revSubstr <- function(x, start, stop) {   x <- strsplit(x, "")   sapply(x,           function(x) paste(rev(rev(x)[start:stop]), collapse = ""),           USE.NAMES = FALSE) } revSubstr(x, start = 1, stop = 2) # [1] "79" "84" "89"  
like image 183
dayne Avatar answered Sep 22 '22 15:09

dayne