首页 > 解决方案 > 如何在r中选择具有特定值的行?

问题描述

我正在尝试编辑我的数据框,但似乎找不到我需要解决这个问题的功能。
我有一个大致如下所示的数据框:

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


(评级介于 1 和 3 之间)

我正在尝试编辑我的数据框,以便获得一个新的数据框,其中评级列没有十进制数字。
即:新的数据框将是:

Title                  Description       Rating
Aladdin                b                 3
Coco                   c                 2

因为 Beaty and the Beast 的评分不是 1、2 或 3。

我觉得 R 中有一个简单的函数,我在 Google 上找不到,我希望有人能提供帮助。

标签: rsortingfilteringsublist

解决方案


我们可以使用subset(from base R) 来比较“Rating”的整数转换值

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

或者,如果我们要与特定的一组值进行比较,请使用%in%

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

数据

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

推荐阅读