Hi all!
I have a very similar dataset to one presented below:
M1 <- matrix(rnorm(100),nrow=100)
M2 <- rep(c("2011", "2012", "2013", "2014"), times = 25)
M1 <- as.data.frame(sapply(M1, as.numeric))
M4 <- cbind(M1, M2)
colnames(M4) <- c("value", "year")
M4[2:5,1] <- 0
Now, what I would like to do is to eliminate "0" in the table and replace them with a mean value grouped by a given year.
I try to use the following code:
M4 <- M4 %>% group_by(year) %>% mutate(nc = if_else(M4[,1] == 0, mean(M4[,1]), M4[,1]))
Unfortunately, I get the following error and I do not know how to solve it using similar solutions. I want to avoid splitting the data frame by year, calculating and then binding it again.
Error: Problem with mutate() column nk.
nk = if_else(M4[, 1] == 0, mean(M4[, 1]), M4[, 1]).
nk must be size 50 or 1, not 200.
The error occurred in group 1: year = "2011".