0

This is my code:

data <- data.frame(x = c(1, 2, NA, 4, 5),
                    y = c(6, 7, NA, 9, 10))

# Calcular a média de todas as colunas, incluindo NA's
mean <- colMeans(dados, na.rm = TRUE)

# Exibir o resultado
mean

Now replacing the Na's by the mean calulated above using replace_na function:

data %>% replace_na(list(mean))

I need to use the replace_na() function Any help?

Laura
  • 675
  • 10
  • 32
  • `list(mean)` creates a `list` with 1 element, the vector of means. Here you want `as.list(mean)`, which makes each element of `mean` a separate element of the list. Compare `list(1:3)` and `as.list(1:3)` to see the difference. – Gregor Thomas May 23 '23 at 20:33
  • Thanks @GregorThomas should I delete this question? – Laura May 23 '23 at 20:35
  • See this answer on the dupe-thread: https://stackoverflow.com/a/56317841/6461462 – M-- May 23 '23 at 21:41
  • No, please don't delete! Duplicates are helpful pointers to where the answers are. – Gregor Thomas May 24 '23 at 14:33

1 Answers1

0

replace_na() could work, but I would recommend sapply() instead:

data <- data.frame(x = c(1, 2, NA, 4, 5),
                   y = c(6, 7, NA, 9, 10))

data[is.na(data)] <- sapply(data, function(x) mean(x, na.rm = TRUE))

print(data)
blitz1259
  • 47
  • 4