Dear Contributors, I hope someone has found a similar issue. I have this data set,
cp1 cp2 role groupid 1 10 13 4 5 2 5 10 3 1 3 7 7 4 6 4 10 4 2 7 5 5 8 3 2 6 8 7 4 4 7 8 8 4 7 8 10 15 3 3 9 15 10 2 2 10 5 5 2 4 11 20 20 2 5 12 9 11 3 6 13 10 13 4 3 14 12 6 4 2 15 7 4 4 1 16 10 0 3 7 17 20 15 3 8 18 10 7 3 4 19 8 13 3 5 20 10 9 2 6 I need to to average of groups, using the values of column groupid, and create a twin dataset in which the mean of the group is replaced instead of individual values. So for example, groupid 3, I calculate the mean (12+18)/2 and then I replace in the new dataframe, but in the same positions, instead of 12 and 18, the values of the corresponding mean. I found this solution, where db10_means is the output dataset, db10 is my initial data. db10_means<-db10 %>% group_by(groupid) %>% mutate(across(starts_with("cp"), list(mean = mean))) It works perfectly, except that for NA values, where it replaces to all group members the NA, while in some cases, the group is made of some NA and some values. So, when I have a group of two values and one NA, I would like that for those with a value, the mean is replaced, for those with NA, the NA is replaced. Here the mean function has not the na.rm=T option associated, but it appears that this solution cannot be implemented in this case. I am not even sure that this would be enough to solve my problem. Thanks for any help provided. -- Francesca ---------------------------------- [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide https://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.