我在聚合数据框时遇到一些麻烦,同时保持组的原始顺序(基于数据框中的第一次出现的顺序).我已经设法做到了,但我希望有一个更简单的方法来解决它.
以下是要处理的示例数据集:
set.seed(7)
sel.1 <- sample(1:5, 20, replace = TRUE) # selection vector 1
sel.2 <- sample(1:5, 20, replace = TRUE)
add.1 <- sample(81:100) # additional vector 1
add.2 <- sample(81:100)
orig.df <- data.frame(sel.1, sel.2, add.1, add.2)
Run Code Online (Sandbox Code Playgroud)
需要注意的一些要点:有两个选择列可确定数据如何组合在一起.他们将是相同的,他们的名字是已知的.我在这些数据中只添加了两列,但可能还有更多.我给出了以'sel'和'add'开头的列名,以便更容易理解,但实际数据有不同的名称(因此虽然grep技巧很酷,但在这里它们没用).
我要做的是根据'sel'列将数据框聚合成组,并将所有'add'列加在一起.这很简单,使用aggregate如下:
# Get the names of all the additional columns
all.add <- names(orig.df)[!(names(orig.df)) %in% c("sel.1", "sel.2")]
aggr.df <- aggregate(orig.df[,all.add],
by=list(sel.1 = orig.df$sel.1, sel.2 = orig.df$sel.2), sum)
Run Code Online (Sandbox Code Playgroud)
问题是结果是由'sel'列排序的; 我希望它根据每个组首次出现在原始数据中进行排序.
以下是我做这项工作的最佳尝试:
## Attempt 1
# create indices for each row …Run Code Online (Sandbox Code Playgroud)