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"
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With