How to remove NA from a dataframe in R?

Asked

Viewed 172 times

0

I have a DF that has some NA, as I will use it to assemble a table, I needed to exchange the NA by " ", to only show the empty space in the table. I am using a mutate_if to leave the numbers to only two decimal places and exchange . for ,.

I tried using the following code, with mutate and replace_na, but it didn’t work, the NA continue to appear.

library(tidyverse)

df %>% 
    mutate_if(is.numeric, format, scientific = FALSE, big.mark = ".", decimal.mark = ",", digits = 2) %>%
    mutate_all(~ replace_na(., NA))

Man dput:

df <- structure(list(a = c("Brasil", "Alimentação no domicílio", 
                           "Arroz", "Feijão-carioca (rajado)", "Farinha de trigo"),
                     b = c(NA, 0.02, 2.71, 9.82, 3.35), c = c(NA, 0.38, 3.69, 10.96, 3.62), 
                     d = c(NA, 0.87, 4.13, 7.28, 3.14), e = c(NA, 1.11, 4.02, 10.09, 3.24), 
                     f = c(NA, 1.13, 4.27, 9.23, 3.43), g = c(NA, NA, 0.15367429760666, 0.0882935186561618, 0.0116253902185224)), 
                row.names = c(NA, 5L), class = "data.frame")

2 answers

1

You can use the [ ], which are a very powerful and underestimated indexing tool, like this:

df[is.na(df)] <- ''
  • Thanks for the excellent solution!

  • 1

    Avoid the use of comments for adjustments, I am happy to note your gratitude, but do not need, let us be as objective as possible, after all, this is what Sopt is based on. I recommend reading the Survival Manual

1


The following solution can do what the question asks.

library(tidyverse)

fun <- function(x) {sub("(^.*\\d,\\d\\d)(.*$)", "\\1", sub("\\.", ",", x))}

df %>%
    mutate(across(everything(), ~replace_na(.x, " "))) %>%
    mutate_at(vars(b:g), fun)
#                         a    b     c    d     e    f    g
#1                   Brasil                                
#2 Alimentação no domicílio 0,02  0,38 0,87  1,11 1,13     
#3                    Arroz 2,71  3,69 4,13  4,02 4,27 0,15
#4  Feijão-carioca (rajado) 9,82 10,96 7,28 10,09 9,23 0,08
#5         Farinha de trigo 3,35  3,62 3,14  3,24 3,43 0,01

Browser other questions tagged

You are not signed in. Login or sign up in order to post.