Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何确定字符串是否为;以“结束”;R中的另一个字符串?_R_String_Ends With - Fatal编程技术网

如何确定字符串是否为;以“结束”;R中的另一个字符串?

如何确定字符串是否为;以“结束”;R中的另一个字符串?,r,string,ends-with,R,String,Ends With,我想过滤掉表中列的字符串值中包含“*”的行。只检查那一栏 string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee") zz <- sapply(tx$variant_full_name, function(x) {substrRight(x, -1) =="*"}) Error in FUN(c("Agno I30N", "VP2 E17Q", "VP2 I204*", "VP3 I85F", "VP1 K73R",

我想过滤掉表中列的字符串值中包含“*”的行。只检查那一栏

 string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")

 zz <- sapply(tx$variant_full_name, function(x) {substrRight(x, -1) =="*"})
 Error in FUN(c("Agno I30N", "VP2 E17Q", "VP2 I204*", "VP3 I85F", "VP1 K73R",  : 
   could not find function "substrRight"
*
是正则表达式中的一种。它告诉正则表达式引擎尝试匹配前面的标记“零次或多次”。要匹配文字,您需要在其前面加两个反斜杠,或将其放在字符类的内部。要检查字符串是否以特定模式结尾,请使用

您只需执行此操作,而无需在base R中实现正则表达式:

> x <- c('aaaaa', 'bbbbb', 'ccccc', 'dddd*', 'eee*eee')
> substr(x, nchar(x)-1+1, nchar(x)) == '*'
# [1] FALSE FALSE FALSE  TRUE FALSE
>x substr(x,nchar(x)-1+1,nchar(x))='*'
#[1]假假假真假假

这非常简单,不需要正则表达式

> string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")
> substring(string_name, nchar(string_name)) == "*"
[1] FALSE FALSE FALSE  TRUE FALSE

我用这样的方式:

strEndsWith <- function(haystack, needle)
{
  hl <- nchar(haystack)
  nl <- nchar(needle)
  if(nl>hl)
  {
    return(F)
  } else
  {
    return(substr(haystack, hl-nl+1, hl) == needle)
  }
}

strengdsWithBase现在包含
startsWith
endsWith
。因此,OP的问题可以用
endsWith
来回答:

> string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")
> endsWith(string_name, '*')
[1] FALSE FALSE FALSE  TRUE FALSE

这比
子字符串(string\u name,nchar(string\u name))=='*'
快得多

这里有一个tidyverse解决方案:

string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")
str_sub(string_name, -1) == "*"
[1] FALSE FALSE FALSE  TRUE FALSE

它的优点是可读性更强,如果需要检查不同的位置,也可以很容易地进行更改。

您可以跳过
*
grepl(“\\*”,“ddddd*”)
。要查找以
*
结尾的字符串,您可以使用
grepl(\\*$,string\u name)
是否可以将其转换为可复制的答案,应用于问题?
> string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")
> endsWith(string_name, '*')
[1] FALSE FALSE FALSE  TRUE FALSE
string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")
str_sub(string_name, -1) == "*"
[1] FALSE FALSE FALSE  TRUE FALSE