Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace 0 or missing value with NA in R [duplicate]

Tags:

r

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

like image 326
jdfhf Avatar asked Feb 05 '19 21:02

jdfhf


3 Answers

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)))
like image 92
acylam Avatar answered Nov 07 '22 00:11

acylam


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)
like image 23
arg0naut91 Avatar answered Nov 07 '22 01:11

arg0naut91


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)))
like image 35
desc Avatar answered Nov 07 '22 00:11

desc