Search code examples
rstartswithdata-management

How to get startsWith function to produce the character instead of the Boolean in R?


As the default, the startsWith function will produce a Boolean output:

x1 <- c("Foobar", "bla bla", "something", "another", "blu", "brown",
        "blau blüht der Enzian")

startsWith(x1, "b")
[1] FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE

How can one use it to get the actual names of the words?


Solution

  • For this we can use grep which have the value argument which by default is FALSE

    grep("^b", x1, value = TRUE)
    

    Or use the logical vector to subset

    x1[startsWith(x1, "b")]