Selva
Selva

Reputation: 2113

Shortest way to check if a word in contained within another word?

What is the shortest way to find out if a word is a subset of another word, keeping the order intact ?

Example: I have two words:

word1 <- "grade", 
word2 <- "upgradeable"
word1 %in% word2    # FALSE

Is there a function that would return TRUE for the above requirement ?

Upvotes: 0

Views: 201

Answers (3)

IRTFM
IRTFM

Reputation: 263481

word1 <- "grade"; word2 <- "upgradeable"
grep(word1, word2)
## [1] 1
grepl(word1, word2)
## [1] TRUE

Read up on regular expression:

?regex

Upvotes: 4

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47282

You could use regexpr, which will also give you the position and length of the matched string:

> regexpr('grade', 'upgradeable')
[1] 3
attr(,"match.length")
[1] 5

The first returned value is TRUE [1] starting at position 3; the second returned value is TRUE [1] with a length of 5.

Upvotes: 2

hwnd
hwnd

Reputation: 70750

You could use the following:

grepl('grade', 'upgradeable')
# [1] TRUE

Upvotes: 1

Related Questions