在R中拆分数据帧的问题

时间:2013-03-07 18:22:55

标签: r split dataframe

我有一个包含1500个数据帧的列表,每个数据帧有3个变量和8行(使用“split”函数生成)

我想通过第2列对所有这些(独立)进行排序,然后,一旦排序,我想消除此列中某个值以下的所有行(第2列)

有什么想法吗?

非常感谢你。

蒂娜。

2 个答案:

答案 0 :(得分:3)

这是一个很小的例子。

# dummy list of data.frames
set.seed(45)
df <- data.frame(V1=sample(8), V2= sample(8), V3 = sample(8))
df.list <- list(df, df, df, df, df, df, df, df)

# function that does the job
df.out <- lapply(df.list, function(x) {
    x[order(x$V2)), ] # order by 2nd column using column name
    x[x$V1 > 3, ] # filter by some criteria
    # you can combine these two lines as:
    # x[order(x$v2)), ][x$v2 > 3, ] (thanks @Ananda for the suggestion)
})

答案 1 :(得分:1)

一些建议:

排序往往是一个缓慢的过程,您可以通过在排序之前先完成子集来加快过程。或者你可能根本不需要排序。

任何时候你想要将数据对象拆分成碎片,对每个碎片应用一个函数,然后将结果重新组合在一起,考虑使用plyr包,它可以使过程更容易。

你的最终目标是什么?有可能以更简单的方式完成整个事情。