Select part of Text in R

1

I would like to filter specific elements of a row, similar to the Excel filter. I have the following example:

NOME    VALOR
LEITO 1 10
LEITO 2 - HPP   20
LEITO 3 - HPP   30
LEITO 4 40

I need to filter, in the name column, lines with the HPP characters. The final result of the filter should look like this:

NOME    VALOR
LEITO 2 - HPP   20
LEITO 3 - HPP   30

How do I make this filter?

    
asked by anonymous 01.12.2017 / 13:15

1 answer

1

The dplyr and stringr packages can help you with this. First, I'll create the dataset:

NOME  <- c("LEITO 1", "LEITO 2 - HPP", "LEITO 3 - HPP", "LEITO 4")
VALOR <- c(10, 20, 30, 40)
dados <- data.frame(NOME, VALOR)

Next, I load the required packages:

library(dplyr)
library(stringr)

Finally, a combination of the filter functions, which selects rows according to some criterion, and str_detect , which searches for a specific chunk of characters within a larger set of characters:

dados %>% 
  filter(str_detect(NOME, "HPP"))
           NOME VALOR
1 LEITO 2 - HPP    20
2 LEITO 3 - HPP    30
    
01.12.2017 / 16:52