0
$\begingroup$

I want to remove a varying number of digits from a date vector. My date vectors looks like this: enter image description here

I want to convert this vector into a date vector, but first I have to get rid of the number in front of it. This is where I struggle since this number can be (here from 88-106) varys in my data.frame from 1-50 000. Does anyone know how to remove these number without destroying the date? I tried the following, but it didn't work out: enter image description here

I would really appreciate your help! Thanks!

$\endgroup$

1 Answer 1

0
$\begingroup$

assuming your strings are of the form [NUMBER][WHITESPACE][STUFF-TO-KEEP]

you can use regex, for example with the stringr package.

# construct strings
strings <- paste(c(1,11,111,1111), "KEEP")
strings
[1] "1 KEEP"    "11 KEEP"   "111 KEEP"  "1111 KEEP"

stringr::str_remove(strings, "[0-9].* (?=[a-zA-Z])")
[1] "KEEP" "KEEP" "KEEP" "KEEP"

the regex "[0-9].* (?=[a-zA-Z])" expained:

'[0-9].* ' # (including the whitespace!) 
# matches any number of digigs from 0 to 9 followed by a whitespace

(?=[a-zA-Z]) 
# this is a lookahead group, so an additional requirement is,
# that a match is only used when the above match is followed
# by a letter in the alphabet, small(a-z) or large (A-Z)

of course, str_remove removes the matches string.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.