如何使用 Stringr 检查向量是否包含 R 中的数字?

How to check if a vector contains numbers in R with Stringr?

使用 R 语言。它说括号和括号的意外标记。该模式似乎也适用。我在这里做错了什么?

if (str_detect(c("Hello 241", "Whawt 602"), [0-9])) {
    print("Oh no!")
} else {
    print("Yay!")
}

答案:"No quotations around regex" 但是:它只检查第一个元素。 如何检查向量中的所有元素?

如果你想检查字符串中是否存在至少一个数字,那么你可以尝试使用这个:

str_detect(c("Hello 241", "Whawt 602"), ".*[0-9].*")

或者也可能是这样的:

str_detect(c("Hello 241", "Whawt 602"), "(?=.*[0-9]).*")

如果您需要单独检查每个单词是否包含数字,请试试这个:

input <- c("Hello 241", "Whawt 602")
output <- sapply(input, function(x) {
    words <- unlist(strsplit(x, "\s+"))
    num_matches <- sapply(words, function(y) str_detect(y, ".*[0-9].*"))
    result <- length(words) == sum(num_matches)
    return(result)
})

if (sum(output) == 0) {
    print("Yay!")
}
else {
    print("Oh no!")
}

可能是这样的:

ifelse(grepl( '[0-9]', c("Hello 241", "Whawt 602",'Nope')),'Oh no!','Yay!')

如果您想一次检查所有元素,只需将 all() 环绕在 grepl:

ifelse(all(grepl( '[0-9]', c("Hello 241", "Whawt 602",'Nope'))),'Oh no!','Yay!')