我正在使用该startsWith功能。我想知道如何让它返回实际的字符串名称而不是布尔值。我也愿意使用其他功能。
startsWith(c("sad_game", "angry_mad", "happy_name"), "happy")
[1] FALSE FALSE TRUE
谢谢!
我正在使用该startsWith功能。我想知道如何让它返回实际的字符串名称而不是布尔值。我也愿意使用其他功能。
startsWith(c("sad_game", "angry_mad", "happy_name"), "happy")
[1] FALSE FALSE TRUE
谢谢!
而不是startsWith,用于动态grep返回值^以指定字符串的开头(编辑 - 基于@Ben Bolker 评论)
grep("^happy", c("sad_game", "angry_mad", "happy_name"), value = TRUE)
[1] "happy_name"
startsWith返回一个逻辑向量。我们需要将逻辑向量作为索引来对原始向量进行子集化
c("sad_game", "angry_mad", "happy_name")[startsWith(c("sad_game",
"angry_mad", "happy_name"), "happy")]
请注意,在上面,我们必须输入两次原始向量。更好的选择是创建一个对象并重用它
v1 <- c("sad_game", "angry_mad", "happy_name")
v1[starts_with(v1, "happy")]
另一种选择是使用str_subsetfromstringr
x <- c("sad_game", "angry_mad", "happy_name")
stringr::str_subset(x, '^happy')
#[1] "happy_name"
这是基于stringi::stri_subset_regex
stringi::stri_subset_regex(x, '^happy')