r语言 - 根据该行中的值在子集中创建(对于每行)最大值的列



我有一个三列的数据帧df。输入两列input1input2,输入一列output

我想在df的子集内创建一个output中最大值的新列,该列基于input1input2低于或等于各自行中各自的输入值的所有行。

我在for循环中很容易做到这一点:

output <- c(1:10)
input1 <- c(5,5,10,10,7,7,20,9,12,18)
input2 <- c(8,6,16,16,8,20,21,12,30,21)
df <- as.data.frame(cbind(output, input1, input2))


for (i in 1:nrow(df)){
df[i,"max"] <- max(df$output[df$input1 <= df$input1[i] &
df$input2 <= df$input2[i]])
}

然而,对于我的原始数据来说,这是不可行的,因为我有多达1,000,000个观测值。

是否有应用或数据内的任何选项。表能加快这个过程吗?

您可以使用fuzzyjoin::fuzzy_inner_join:

library(dplyr)
fuzzyjoin::fuzzy_inner_join(df, df, 
by = c('input1', 'input2'), 
match_fun = c(`>=`, `>=`)) %>% 
group_by(output = output.x, input1 = input1.x, input2 = input2.x) %>%
summarise(max = max(output.y))
#   output input1 input2   max
#    <dbl>  <dbl>  <dbl> <dbl>
# 1      1      5      8     2
# 2      2      5      6     2
# 3      3     10     16     8
# 4      4     10     16     8
# 5      5      7      8     5
# 6      6      7     20     6
# 7      7     20     21    10
# 8      8      9     12     8
# 9      9     12     30     9
#10     10     18     21    10

最新更新