Search code examples
rsortingfilteringsublist

How to select rows with a certain value in r?


I am trying to edit my dataframe but cannot seem to find the function that I need to sort this out.
I have a dataframe that looks roughly like this:

Title                  Description       Rating
Beauty and the Beast   a                 2.5
Aladdin                b                 3
Coco                   c                 2

etc.
(rating is between 1 and 3)

I am trying to edit my dataframe so that I get a new dataframe where there is no decimal numbers for the rating column.
i.e: the new dataframe would be:

Title                  Description       Rating
Aladdin                b                 3
Coco                   c                 2

As Beaty and the Beast's rating is not 1, 2 or 3.

I feel like there's a simple function in R that I just cannot find on Google, and I was hoping someone could help.


Solution

  • We can use subset (from base R) with a comparison on the integer converted values of 'Rating'

    subset(df1, Rating == as.integer(Rating))
    #    Title Description Rating
    #2 Aladdin           b      3
    #3    Coco           c      2
    

    Or if we are comparing with specific set of values, use %in%

    subset(df1, Rating %in% 1:3)
    

    data

    df1 <- structure(list(Title = c("Beauty and the Beast", "Aladdin", "Coco"
    ), Description = c("a", "b", "c"), Rating = c(2.5, 3, 2)),
    class = "data.frame", row.names = c(NA, 
    -3L))