Home > OS >  dplyr median by group
dplyr median by group

Time:11-01

I have this data frame

df1 <- data.frame(
     Type1 = c("A","A","A", "AB", "AB"),
     Type2 = c(1L,2L,2L, 1L, 1L),
     Value = c(1L, 2L, 1L, NA, NA), , Median = c(1L, 1.5, 1.5, NA, NA))

I would like to get median in a new column by Type1 and Type2 to a new variable "AB" without summarise to have a new value in existing column.

 df12 <- data.frame(
    Type1 = c("A","A","A", "AB", "AB"),
    Type2 = c(1L,2L,2L, 1L, 1L),
    Value = c(1L, 2L, 1L, NA, NA), Median = c(1L, 1.5, 1.5, 1L, 1L))

My try

df1 %>% group_by(Type1, Type2) %>% mutate(Median = ifelse(Type1 == "AB" & Type2 == 1, median(Value), Median))

CodePudding user response:

We may need to remove the grouping here

library(dplyr)
df1 %>%
    mutate(Median = replace(Median, Type1 %in% 'AB' & Type2 %in% 1, 
        median(Value, na.rm = TRUE)) )
  • Related