简体   繁体   English

在R中按组和条件查找列的最大值

[英]Finding the max value of a column by group and condition in R

I have two data.tables in R. 我在R中有两个data.tables。

Table A has ID_A, days, and group. 表A具有ID_A,天数和组。

Table B has ID_B, days, group, and value_of_interest. 表B具有ID_B,天,组和value_of_interest。

I'm trying to add a column to A, max_value_of_interest, where the value is the maximum of the value_of_interest in all rows of a group where the days in B is greater than days in table A. 我正在尝试向A添加一列max_value_of_interest,其中值是B中的天数大于表A中的天数的组中所有行中value_of_interest的最大值。

I'll try to describe it another way: 我将尝试用另一种方式描述它:

Table A: 表A:

ID_A    days    group
A1      5       X

I want to add a column to A containing the maximum value_of_interest from B, where the maximum value is chosen from B where B.group=X and B.days > 5 (greater than the value in row A1). 我想向A添加一列,其中包含B的maximum_of_interest,其中从B.group = X且B.days> 5(大于A1行中的值)的B中选择最大值。

I've found solutions for finding the maximum by group, but I'm having trouble figuring out how to add in a condition to consider only values where B.days by group > A.days. 我已经找到了用于按组查找最大值的解决方案,但是我很难弄清楚如何添加条件以仅考虑按组B.days> A.days的值。

I'm not sure of the best way to approach this. 我不确定解决此问题的最佳方法。 I'd appreciate any help. 我将不胜感激。

It might be easiest to loop through the rows of Table A. For each row, select the relevant rows of B, then find the max value. 遍历表A的行可能是最简单的。对于每一行,选择B的相关行,然后找到最大值。

library(tidyverse)
A <- tibble(ID_A=paste("A", 1:5, sep=""), 
            days=seq(5,1,-1), 
            group=c("X", "X", "X", "Y", "Y"),
            max_val=NA)
B <- tibble(ID_B=paste("A", 1:5, sep=""), 
            days=seq(3,7,1), 
            group=c("X", "X", "X", "Y", "Y"),
            val=runif(5))

for (i in 1:nrow(A)){
  B_sel <- B %>%
    filter(group==A$group[i] & days>A$days[i]) 
  if (nrow(B_sel)>0)
    A$max_val[i] <- max(B_sel$val)
}

or 要么

for (i in 1:nrow(A)){
  rows <- which(B$group==A$group[i] & B$days>A$days[i]) 
  if (length(rows)>0)
    A$max_val[i] <- max(B$val[rows])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM