Search code examples
rstringstartswith

How to get startsWith function to return values, not Boolean


I am using the startsWith function and I want it to return values, not Booleans.

string <- ("dem_seat", "factor(state)CT", "factor(state)DE")
startsWith(string , "factor(state)")
> FALSE  TRUE  TRUE

I'd like it to return:

> "factor(state)CT" "factor(state)DE"

Solution

  • We can use grep with value = TRUE (by default, it return the numeric index or position index)

    grep("^factor\\(state\\)", string, value = TRUE)
    

    If we have a logical vector, we can use that as index to subset

    string[startsWith(string , "factor(state)")]