0

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)
3
  • 1
    It's very helpful to provide data if you'd like help more quickly. That said, check out dplyr::mutate_all , as I think that should provide you a quick solution. Commented Jun 22, 2018 at 20:41
  • What have you tried so far? Can you provide an example input dataset and desired output dataset? Can you be more specific about "etc"? Commented Jun 22, 2018 at 20:43
  • I have updated my question with a simple example. I can replace column-wise but my actual dataframe has hundreds of columns and thousands of rows! Commented Jun 22, 2018 at 20:45

1 Answer 1

4

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 
Sign up to request clarification or add additional context in comments.

1 Comment

@zack, for the sake of completeness, I included your purrr::map_df() suggestion from three days ago. I'm happy to remove it if you submit a separate answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.