如何编写程序对重复观测值按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
相关产品推荐
相关产品推荐

