Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep at the beginning of the string with fixed =T in R?

Tags:

regex

r

How to grep with fixed=T, but only at the beginning of the string?

grep("a.", c("a.b", "cac", "sss", "ca.f"), fixed = T)
# 1 4

I would like to get only the first occurrence. [Edit: the string to match is not known in advance, and can be anything. "a." is just for the sake of example]

Thanks.

[Edit: I sort of solved it now, but any other ideas are highly welcome. I will accept as an answer any alternative solution.

s <- "a."
res <- grep(s, c("a.b", "cac", "sss", "ca.f"), fixed = T, value = T)
res[substring(res, 1, nchar(s)) == s]

]

like image 421
VitoshKa Avatar asked Dec 18 '10 10:12

VitoshKa


People also ask

How do you grep at the beginning of a line?

Use the ^ (caret) symbol to match expression at the start of a line. In the following example, the string kangaroo will match only if it occurs at the very beginning of a line. Use the $ (dollar) symbol to match expression at the end of a line.

What is fixed in Grepl?

fixed = TRUE just tells grep there is no regular expression in the pattern . fixed=TRUE means that the pattern shouldn't be considered a regex , but just as it is. Your vector contains the substring YES and so the match.

Can you use grep in R?

grep() function in R Language is used to search for matches of a pattern within each element of the given string. Parameters: pattern: Specified pattern which is going to be matched with given elements of the string.

What does the Grepl () function do?

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

If you want to match an exact string (string 1) at the beginning of the string (string 2), then just subset your string 2 to be the same length as string 1 and use ==, should be fairly fast.

like image 87
Greg Snow Avatar answered Oct 31 '22 14:10

Greg Snow