ip2018
ip2018

Reputation: 715

Replace all 0 values with 1 in dataframe with multiple rows and columns at once

How can I replace all NA, NaN, 0, 0.00, 0.000 values with 1 in dataframe with multiple rows and columns at once? Thanks.

An example df:

a = c(233, 0, NA, 3455)
b = c(23, 0.000, NA, 345)
c = c(223, 0.00, NaN, 30055)

df = cbind.data.frame(a,b,c)

Upvotes: 0

Views: 181

Answers (1)

wibeasley
wibeasley

Reputation: 5287

I like @zack's suggested dplyr::mutate_all(). Another option is purrr::map_df().

scrub <- function( x ) {
  x <- dplyr::if_else(dplyr::near(x, 0), 1, x)
  x <- dplyr::coalesce(x, 1)
  x
}

# Option 1 (These four lines are equivalent):
df %>%                                  # This needs `library(magrittr)` 
  purrr::map_df(scrub)
purrr::map_df(df, scrub)
purrr::map_df(df, ~scrub(.))
purrr::map_df(df, function(x) scrub(x))

# Option 2, suggested by @zack in the comments:
dplyr::mutate_all(df, scrub)

Here is the result from purrr::map_df(), which is a tibble. The dplyr::mutate_all() returns a data.frame.

# A tibble: 4 x 3
      a     b     c
  <dbl> <dbl> <dbl>
1   233    23   223
2     1     1     1
3     1     1     1
4  3455   345 30055 

Upvotes: 4

Related Questions