9

this is what i have already done so far data is numeric data type

if (is.na(data) || attribute==0){replace(data,NA)}

it gives me error message that

Error in replace(attribute, NA) : argument "values" is missing, with no default

acylam
  • 18,231
  • 5
  • 36
  • 45
jdfhf
  • 163
  • 1
  • 1
  • 7

3 Answers3

10

With mutate_all:

library(dplyr)

df %>%
  mutate_all(~replace(., . == 0, NA))

or with mutate_if to be safe:

df %>%
  mutate_if(is.numeric, ~replace(., . == 0, NA))

Note that there is no need to check for NA's, because we are replacing with NA anyway.

Output:

> df %>%
+   mutate_all(~replace(., . == 0, NA))
    X  Y    Z
1   1  5 <NA>
2   4  4    2
3   2  3    2
4   5  5    2
5   5  3 <NA>
6  NA  4 <NA>
7   3  3    1
8   5  3    2
9   3  1    1
10  2 NA    5
11  5  5 <NA>
12  2  5    2
13  4  4    4
14  3  4 <NA>
15 NA NA    3
16  5  2    1
17  1  4 <NA>
18 NA  1    4
19  1  1    5
20  5  1    2

> df %>%
+   mutate_if(is.numeric, ~replace(., . == 0, NA))
    X  Y Z
1   1  5 0
2   4  4 2
3   2  3 2
4   5  5 2
5   5  3 0
6  NA  4 0
7   3  3 1
8   5  3 2
9   3  1 1
10  2 NA 5
11  5  5 0
12  2  5 2
13  4  4 4
14  3  4 0
15 NA NA 3
16  5  2 1
17  1  4 0
18 NA  1 4
19  1  1 5
20  5  1 2

Data:

set.seed(123)
df <- data.frame(X = sample(0:5, 20, replace = TRUE),
                 Y = sample(0:5, 20, replace = TRUE),
                 Z = as.character(sample(0:5, 20, replace = TRUE)))
acylam
  • 18,231
  • 5
  • 36
  • 45
  • can you please tell me how to import the library you were mentioning about, because it doesn't allow me to use mutate_all. I'm testing it on R_markdown – jdfhf Feb 05 '19 at 21:30
  • @jdfhf `install.packages('dplyr')` then `library(dplyr)` should give you the latest version. Your version of `dplyr` is probably outdated. – acylam Feb 05 '19 at 21:48
6

You could just use replace without any additional function / package:

data <- replace(data, data == 0, NA)

This is now assuming that data is your data frame.

Otherwise you can simply insert the column name, e.g. if your data frame is df and column name data:

df$data <- replace(df$data, df$data == 0, NA)
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
  • this is the best solution with base r. if someone wants a dplyr solution, then the simplest would be `df %>% map_df(~ na_if(.x, 0))` – Agile Bean Dec 09 '21 at 12:31
2

Assuming that data is a dataframe then you could use sapply to update your values based on a set of filters:

new.data = as.data.frame(sapply(data,FUN= function(x) replace(x,is.na(x) | x == 0)))
desc
  • 1,190
  • 1
  • 12
  • 26