如何选择空格后的第一个字符

问题描述 投票:0回答:2

我想在空格后选择第一个字符。我的MWE是由

Input

a <- c("United States", "South America")
a

Output desired

"S" "A"
r regex string
2个回答
3
投票

base-R的例子:

gsub(".* (\\C).*", "\\1", a, perl = TRUE)
[1] "S" "A"

3
投票
inds = regexpr(" ", a) + 1
substring(a, inds, inds)
#[1] "S" "A"

或者使用str_extractstringr

library(stringr)
str_extract(string = a, pattern = "(?<=\\s).")
#[1] "S" "A"
© www.soinside.com 2019 - 2024. All rights reserved.