根据逻辑条件在行的子集上对数据帧进行子集 [英] Subsetting a data frame based on a logical condition on a subset of rows

查看:48
本文介绍了根据逻辑条件在行的子集上对数据帧进行子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图提出一种解决Followig问题的简单方法.这是最小的工作示例:

I've tried to come up with a simple solution to the followig problem. Here is the minimum working example:

data <- data.frame(subject = c('Math', 'English', 'French', 'English'),
                   grade = c(1, 3, 5, 4))

我想要一个比较Enlish成绩并返回逻辑矢量的函数,该逻辑矢量对于英语成绩最高的行为TRUE,对于所有其他行为FALSE.在这种情况下, [1]否否否是.

I want a function that compares Enlish grades and returns a logical vector that has TRUE for the row with the highest english grade, and FALSE for all other rows. In this case [1] FALSE FALSE FALSE TRUE.

推荐答案

我们可以通过 ave 与成绩"以获取逻辑索引,并检查主题"是否也为英语"

We can get the max 'grade' per 'subject' with ave compare it with the 'grade' to get a logical index and check whether the 'subject' is also 'English'

with(data, ave(grade, subject, FUN = max)==grade & subject == "English") 
#[1] FALSE FALSE FALSE  TRUE

这篇关于根据逻辑条件在行的子集上对数据帧进行子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆