按因子级别对数据帧进行子集 [英] Subsetting data frame by factor level

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

问题描述

我有一个大数据框,在一个列中有状态名称,在另一列中有不同的索引. 我想按状态进行子集创建一个对象,该对象适合于已给出计算的索引或数据帧的最小化.

I have a big data frame with state names in one colum and different indexes in the other columns. I want to subset by state and create an object suitable for minimization of the index or a data frame with the calculation already given.

这是我所拥有的一个简单(简短)示例

Here's one simple (short) example of what I have

m
  x   y
1 A 1.0
2 A 2.0
3 A 1.5
4 B 3.0
5 B 3.5
6 C 7.0

我想要这个

m
  x y
1 A 1.0
2 B 3.0
3 C 7.0

我不知道带有for循环的函数是否必要.像

I don't know if a function with a for loop is necessary. Like

minimize<-function(x,...)
for (i in m$x){ 
do something with data by factor value 
apply to that something the min function in every column
return(y)
} 

所以当您打电话

minimize(A)
[1] 1

我尝试使用%in%,但没有用(我收到此错误).

I tried to use %in% but didn't work (I got this error).

A%in%m match(x,table,nomatch = 0L)错误:找不到对象'A'

A%in%m Error in match(x, table, nomatch = 0L) : object 'A' not found

当我定义它时,它就是这样.

When I define it it goes like this.

A<-c("A")
"A"%in%m
[1] FALSE

提前谢谢

推荐答案

尝试aggregate:

aggregate(y ~ x, m, min)

  x y
1 A 1
2 B 3
3 C 7

这篇关于按因子级别对数据帧进行子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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