假设有一个带ID列的有序df,其他包含数字数据的列按最后一列排序。
ID <- c(123, 142, 21, 562, 36, 721, 847, 321)
A <- c(96, 83, 73, 47, 88, 65, 72, 67)
B <- c(72, 69, 88, 75, 63, 89, 48, 80)
C <- c(95, 94, 94, 94, 65, 81, 75, 75)
D <- c(63, 88, 89, 88, 89, 79, 88, 79)
Rating <- c(97, 95, 92, 87, 85, 83, 79, 77)
df <- data.frame(ID, A, B, C, D, Rating)
df
# ID A B C D Rating
#1 123 96 72 95 63 97
#2 142 83 69 94 88 95
#3 21 73 88 94 89 92
#4 562 47 75 94 88 87
#5 36 88 63 65 89 85
#6 721 65 89 81 79 83
#7 847 72 48 75 88 79
#8 321 67 80 75 79 77
目的是获取每个组/列的最大值及其ID,并且每对/每个对都必须来自不同的行(唯一ID)。对于同一列具有相同值的两个ID,请选择评分较高的ID。
我所做的是使用apply()函数从每一列中获取最大值,提取具有该值的ID,然后将它们全部连接到数据框中。因为我仍然缺少第4列的ID,所以我使用了反联接来取出之前的ID,并重复此过程以获取此数据帧:
my_max <- data.frame(apply(df, 2, max))
A2 <- df[which(df$A == my_max[2,1]),]%>% dplyr::select(ID, A)
B2 <- df[which(df$B == my_max[3,1]),]%>% dplyr::select(ID, B)
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
D2 <- df[which(df$D == my_max[5,1]),]%>% dplyr::select(ID, D)
all <- full_join(A2, B2, by='ID') %>% full_join(C2, by='ID') %>% full_join(D2, by='ID')
all <- all[-c(4),]
df <- anti_join(df, all, by='ID')
my_max <- data.frame(apply(df, 2, max))
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
all <- all %>% full_join(C2, by='ID')
all <- all[-c(5),-c(4)]
最后给我:
all
# ID A B D C.y
#1 123 96 NA NA NA
#2 721 NA 89 NA NA
#3 21 NA NA 89 NA
#4 142 NA NA NA 94
有没有更简洁或简洁/有效的方法?不一定是相同的方式,也许只是ID和角色类似:
# ID Group
#1 123 A
#2 721 B
#3 142 C
#4 21 D
我看到某些解决方案不处理重复的ID。例如,对于组A和C,我们都有ID 123。
为了获得与您的问题的最终结果相似的输出,以下是处理重复ID的另一种解决方案:
# initialization
variables <- c("A", "B", "C", "D")
df_max <- data.frame(ID = numeric(length(variables)), Group = variables)
for(column in variables){
temp_id <- df %>%
filter(!(ID %in% df_max$ID)) %>%
arrange(desc(!!rlang::sym(column)), desc(Rating)) %>%
slice(1) %>%
select(ID) %>%
as.numeric(ID)
df_max[df_max$Group == column, "ID"] <- temp_id
}
基本上,该filter
步骤确保我们不考虑已经选择的ID。
输出量
# > df_max
#
# ID Group
# 1 123 A
# 2 721 B
# 3 142 C
# 4 21 D
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句