In R you can use na.aggregate/data.table to replace the value of NA with mean groups. We convert "data.frame" to "data.table" ( setDT(df) ), grouped by "A", apply na.aggregate to "B".
library(zoo) library(data.table) setDT(df)[, B:= na.aggregate(B), A] df # AB #1: apple 1.0 #2: apple 2.0 #3: apple 1.5 #4: orange 7.0 #5: orange 7.0 #6: melon 14.0 #7: melon 15.0 #8: melon 15.0 #9: melon 16.0
akrun source share