通过为每组选择一行来折叠数据框 [英] Collapsing data frame by selecting one row per group

查看:22
本文介绍了通过为每组选择一行来折叠数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过从特定列中具有相同值的每组行中删除除一行之外的所有行来折叠数据框.换句话说,每组的第一行.

I'm trying to collapse a data frame by removing all but one row from each group of rows with identical values in a particular column. In other words, the first row from each group.

例如,我想转换这个

> d = data.frame(x=c(1,1,2,4),y=c(10,11,12,13),z=c(20,19,18,17))
> d
  x  y  z
1 1 10 20
2 1 11 19
3 2 12 18
4 4 13 17

进入这个:

    x  y  z
1   1 11 19
2   2 12 18
3   4 13 17

我目前正在使用聚合来执行此操作,但使用更多数据时性能无法接受:

I'm using aggregate to do this currently, but the performance is unacceptable with more data:

> d.ordered = d[order(-d$y),]
> aggregate(d.ordered,by=list(key=d.ordered$x),FUN=function(x){x[1]})

我已经尝试使用与此处相同的函数参数进行 split/unsplit,但 unsplit 会抱怨重复的行号.

I've tried split/unsplit with the same function argument as here, but unsplit complains about duplicate row numbers.

有可能吗?是否有 R 习惯用法将 rle 的长度向量转换为每次运行开始的行的索引,然后我可以使用它从数据框中提取这些行?

Is rle a possibility? Is there an R idiom to convert rle's length vector into the indices of the rows that start each run, which I can then use to pluck those rows out of the data frame?

推荐答案

也许 duplicated() 可以提供帮助:

Maybe duplicated() can help:

R> d[ !duplicated(d$x), ]
  x  y  z
1 1 10 20
3 2 12 18
4 4 13 17
R> 

编辑糟糕,没关系.这将在每个重复块中选择第一个,您想要最后一个.所以这是使用 plyr 的另一种尝试:

Edit Shucks, never mind. This picks the first in each block of repetitions, you wanted the last. So here is another attempt using plyr:

R> ddply(d, "x", function(z) tail(z,1))
  x  y  z
1 1 11 19
2 2 12 18
3 4 13 17
R> 

这里 plyr 完成了寻找唯一子集、循环它们并应用的艰苦工作提供的函数——它使用 tail(z, 1) 简单地返回块 z 中的最后一组观察值.

Here plyr does the hard work of finding unique subsets, looping over them and applying the supplied function -- which simply returns the last set of observations in a block z using tail(z, 1).

这篇关于通过为每组选择一行来折叠数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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