I’m trying to pivot_wider, and want to fill NA cells with the mean of their respective columns, but I’m running into issues with the values_fill= part of the argument.
Here’s the pivot without the fill:
x <- df_long %>%
pivot_wider(names_from = genus, values_from = mean_weight)
“wide df” has NA in cells as expected
I saved it to x so that I can get the averages of these columns.
My issue is I don’t know how to fill in the *** in the next line. Is there a way to get this in one line? Or do I need another pipe?
df_long %>%
pivot_wider(names_from = genus, values_from = mean_weight, values_fill = mean(***, na.rm = TRUE))
I tried:
df_long %>%
pivot_wider(names_from = genus, values_from = mean_weight, values_fill = mean(x$genus == "genus", na.rm =T))
All this does is fill the NA spots with 0.
I know a more traditional loop is also possible:
for (i in 2:ncol(x)){
x[,i][is.na(x[,i])] <- mean(x[[i]],na.rm=T)
}
If someone can help me with tidy logic so I can do this all with pipes (fix the values_fill= parameter), I would greatly appreciate your time and expertise.
F4G4opener is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.