Reputation: 245
Basically, I'd like to keep only the first character in a vector, I know this can be done in substr() easily, but I'd like to know how to do it in gsub().
For example,
codes <- c("02Q","4E (1)","4S (1)","A0","A2","A4")
I want a result vector like
c("0","4","4","A","A","A")
Thanks
Upvotes: 1
Views: 2571
Reputation: 174796
Seems you did like to keep only the first character.
gsub("(?<!^).", "", codes, perl=TRUE)
# [1] "0" "4" "4" "A" "A" "A"
(?<!^)
negative lookbehind which asserts that the match would be preceeded by any but not the start of a line boundary.
or
codes <- c("02Q","4E (1)","4S (1)","A0","A2","A4")
sub("(?<!^).*", "", codes, perl=T)
[1] "0" "4" "4" "A" "A" "A"
Few more..
> sub("(?!^.).*", "", codes, perl=T)
[1] "0" "4" "4" "A" "A" "A"
> sub("\\B.*", "", codes, perl=T)
[1] "0" "4" "4" "A" "A" "A"
Upvotes: 4
Reputation: 24074
you can do
sub("^(\\w).*$", "\\1", codes)
#[1] "0" "4" "4" "A" "A" "A"
Explanation:
Upvotes: 6