You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写程序对重复观测值按ID取A、B变量最大值填充?

Solution to Fill Groupwise Max Values

Base R Approach

Use the ave() function to calculate the maximum value of A and B for each ID, then overwrite the original columns with these group-specific maxima.

# Update column A with ID-wise max
j$A <- ave(j$A, j$ID, FUN = max)
# Update column B with ID-wise max
j$B <- ave(j$B, j$ID, FUN = max)

# Check the result
j

Result:

ID  A  B
1 22 10  8
2 22 10  8
3 23 60 10
4 23 60 10
5 23 60 10
6 23 60 10

dplyr Approach

For tidy data manipulation, use the dplyr package to group by ID and mutate columns to their group maxima:

library(dplyr)

j <- j %>%
  group_by(ID) %>%
  mutate(
    A = max(A),
    B = max(B)
  ) %>%
  ungroup()

# Check the result
j

Result:

# A tibble: 6 × 3
     ID     A     B
  <int> <int> <int>
1    22    10     8
2    22    10     8
3    23    60    10
4    23    60    10
5    23    60    10
6    23    60    10

内容的提问来源于stack exchange,提问作者Zebu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:33:19