【发布时间】:2021-03-01 20:49:46
【问题描述】:
我有一个具有 $ID、$Age 和 $Score 特征的数据框。我想将其过滤为分数低于特定值的唯一 ID。对于多个分数低于阈值的 ID,我只想保留最旧的(即最大年龄)。
这是我尝试实现它的方法,但由于循环,它很慢。有没有办法使用 dplyr 或类似的库来加快速度?
#find the indexes of the items below the threshold
idx <- df$Score <= threshold
#select the below threshold rows
df <- df[idx,]
#find the unique IDs
unique_ids <- unique(df$ID)
unique_items <- data.frame(matrix(ncol=3, nrow=length(unique_ids)))
colnames(unique_items) <- colnames(df)
#loop through each unique ID
for(i in 1:length(unique_ids))
{
#find all the items that match that unique ID
my.list <- df[df$ID == unique_ids[i],]
#find the index of the oldest unique item that is below the threshold
oldest_idx <- which.max(my.list$Age)
#assign it the the result dataframe
unique_items[i,] <- my.list[oldest_idx,]
}
【问题讨论】: