rama27
rama27

Reputation: 185

How to subset a dataframe by unique character in R?

I would like to create a new dataframe from existing one. My df looks like this:

X                Y
12            ABC_SS
23            B49
45            G56_SS

I would like to subset new dataset that will have only Y values that includes "_SS" in Y. How can i do that, please?

This doesnt work:

newdf <-subset(df,df$Y %in% "_SS")

Upvotes: 0

Views: 118

Answers (1)

akrun
akrun

Reputation: 887851

We can use grepl in base R to match substring

subset(df, grepl("_SS", Y))

Or another option is filter

library(dplyr)
library(stringr)
df %>%
     filter(str_detect(Y, "_SS$"))

Upvotes: 2

Related Questions