R 根据列的聚合函数对数据帧的行进行排序
我有一个包含两列的数据框,id和value,以及超过100k的观察值 大约有1000个不同的ID 我想创建两个新的数据帧,其中的数据与原始数据帧相同,但行按照以下标准排序 对于一个数据帧,如果两行r1和r2分别具有id1和id2,并且如果id=id1的行数小于id=id2的行数,则r1应出现在r2之前 对于另一个数据帧,如果两行r1和r2具有id id1和id2,并且id=id1的行的最大值小于id=id2的行的最大值,则r1应出现在r2之前 这两种排序是根据列的聚合函数定义的,因此创建这种排序的解决方案将允许创建更大的排序类别 如何在R中高效地构建这样的订单 编辑: 这是我的代码,它可以工作,但速度慢,时间长。我想知道是否有更聪明、更快捷的方法R 根据列的聚合函数对数据帧的行进行排序,r,aggregate-functions,R,Aggregate Functions,我有一个包含两列的数据框,id和value,以及超过100k的观察值 大约有1000个不同的ID 我想创建两个新的数据帧,其中的数据与原始数据帧相同,但行按照以下标准排序 对于一个数据帧,如果两行r1和r2分别具有id1和id2,并且如果id=id1的行数小于id=id2的行数,则r1应出现在r2之前 对于另一个数据帧,如果两行r1和r2具有id id1和id2,并且id=id1的行的最大值小于id=id2的行的最大值,则r1应出现在r2之前 这两种排序是根据列的聚合函数定义的,因此创建这种排序
library(hashmap)
a <- read.table(filename, header = T)
aggregate_values <- unlist(lapply(unique(a[[1]]), function(x) max(a[a[[1]] == x,2])))
id_to_aggregate_value <- hashmap(unique(a[[1]]), aggregate_values)
aggregate_values_columns <- id_to_aggregate_value[[a[[1]]]]
a <- cbind(a, aggregate_values_columns)
a <- a[order(a[,3]),]
这种操作是data.table包擅长的。谢谢,我不知道,我会试试看
library(dplyr)
# Make a similar table as yours with ~1000 ids and 100k rows
df <- tibble(
id = rnorm(n = 1E5, mean = 1000, sd = 150) %>% as.integer(),
value = runif(1E5, 500, 1500)
)
# How many unique id's? Should be around 1000...
length(unique(df$id))
[1] 1052
# First question, show infrequent id's first
df_sort_by_id_freq <- df %>%
add_count(id) %>%
arrange(n, id)
# Second question, show id's with smallest max first
df_sort_by_max <- df %>%
group_by(id) %>%
mutate(id_max = max(value)) %>%
arrange(id_max, id, value)