Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a string "ends with" another string in R?

I want to filter out the rows of a table which contain '*' in the string value of the column. Checking just that column.

 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"

The 4th value of zz should be TRUE by this.

in python there is endswith function for strings [ string_s.endswith('*') ] Is there something similar to that in R ?

Also, is it problem because of '*' as a character as it means any character ? grepl also not working.

> grepl("*^",'dddd*')
[1] TRUE
> grepl("*^",'dddd')
[1] TRUE
like image 458
Malaya Avatar asked Oct 04 '14 01:10

Malaya


People also ask

How do you check if a string ends with another string?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive. See also the startswith() method.

How do you check if a string contains another string in R?

In R, we use the grepl() function to check if characters are present in a string or not. And the method returns a Boolean value, TRUE - if the specified sequence of characters are present in the string.

What is Grepl R?

The grepl() stands for “grep logical”. In R it is a built-in function that searches for matches of a string or string vector. The grepl() method takes a pattern and data and returns TRUE if a string contains the pattern, otherwise FALSE.


1 Answers

Base now contains startsWith and endsWith. Thus the OP's question can be answered with endsWith:

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

This is much faster than substring(string_name, nchar(string_name)) == '*'.

like image 161
Vidhya G Avatar answered Sep 30 '22 17:09

Vidhya G