简体   繁体   中英

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.
ie: 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.

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))

You can get the remainder after dividing by 1 and select rows where the remainder is 0.

subset(df, Rating %% 1 == 0)

#    Title Description Rating
#2 Aladdin           b      3
#3    Coco           c      2

You want to use the dplyr function in R

  library(dplyr)

  df1 %>%
    filter(R != 2.5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM