r - 为大型数据集从 R 中的 data.frame 中获取前 N 个排序元素

标签 r sorting dataframe plyr

我对 R 比较陌生,所以这可能是一个简单的问题。我尝试广泛搜索答案,但找不到答案。

我有一个表格中的数据框:

firstword  nextword   freq
a          little     23
a          great      46
a          few        32
a          good       15
about      the        57
about      how        34
about      a          48 
about      it         27
by         the        36
by         his        52
by         an         12
by         my         16

这只是我数据集中的一个小样本,用于说明。我的数据框超过一百万行。 firstword 和 nextword 是字符类型。每个 firstword 可以有许多 nextwords 与之关联,而有些可能只有一个。

如何从中生成另一个数据帧,以便按 desc 排序。每个 'firstword' 的频率顺序,最多只包含前 6 个 nextwords。

我尝试了以下代码。

small = ddply(df, "firstword", summarise, nextword=nextword[order(freq,decreasing=T)[1:6]])

这适用于我的数据的较小子集,但是当我对整个数据运行它时内存不足。

最佳答案

这是一种使用 data.table 包的类似有效方法。 首先,您不需要在every组中排列freq,只排序一次就足够了,效率更高。所以一种方法很简单

library(data.table)
setDT(df)[order(-freq), .SD[seq_len(6)], by = firstword]

另一种方法(可能更有效)是使用 .I 参数(Index)查找索引,然后查找子集

indx <- df[order(-freq), .I[seq_len(6)], by = firstword]$V1
df[indx]

关于r - 为大型数据集从 R 中的 data.frame 中获取前 N 个排序元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29842454/

相关文章:

python - PySpark:向数据框行元素添加新字段

python - 如何在 pd.dataframe 的特定组中找到相交和唯一的字符串?

r - 如何在R中绘制时间序列数据,根据因子数据改变背景?

arrays - 合并 k 个排序数组 - 比较两个解决方案

r - 如何循环和修改R中的多个数据帧

javascript - 使用数组作为排序顺序

javascript - 找到一组数字的最大值(JS)

python - 尝试循环 DataFrame 中的列并剥离美元符号

r - 具有大量数据的热图

linux - 完全卸载r linux