1

For each unique id, I want to find the max(G) and then repeat it in a new column called G2.

Is this possible in BASE R?

Here is a toy input and its desired output:

INPUT = data.frame(id = c(1,1,2,2,2), G = 1:5)
#  id G
#1  1 1
#2  1 2
#3  2 3
#4  2 4
#5  2 5
  
DESIRED_OUTPUT = data.frame(id = c(1,1,2,2,2), G = 1:5, G2 = c(3,3,5,5,5))
#  id G G2
#1  1 1  2
#2  1 2  2
#3  2 3  5
#4  2 4  5
#5  2 5  5
rnorouzian
  • 7,397
  • 5
  • 27
  • 72

1 Answers1

1

With base R, use ave

INPUT$G2 <- with(INPUT, ave(G, id, FUN = function(x) max(x, na.rm = TRUE))

or in dplyr

library(dplyr)
INPUT %>%
      group_by(id) %>% 
      mutate(G2 = max(G)) %>%
      ungroup
akrun
  • 874,273
  • 37
  • 540
  • 662