I have a data set with N/A appearing but the N/A means 0 so it isn't a missing value as such. Specifically, where there is no garage the data is N/A. I've followed the usual path to change to numeric, but it isn't working for me. I'm new to r so I have limited knowledge, but it's driving me nuts. How should I deal with this issue?
Asked
Active
Viewed 302 times
0
-
Have you tried `mydata[is.na(mydata)] <- 0` – Daniel O Apr 06 '21 at 01:23
-
2Please see my answer to see if this works or if you have any questions. In the future, it is better to include a reproducible example. It will make others easier to answer your question. – www Apr 06 '21 at 01:26
-
One of this link should work for you https://stackoverflow.com/questions/8161836/how-do-i-replace-na-values-with-zeros-in-an-r-dataframe. If you have string "NA" use `mydata[mydata == 'NA'] <- 0` like in this link https://stackoverflow.com/questions/11036989/replace-all-0-values-to-na – Ronak Shah Apr 06 '21 at 01:35
2 Answers
0
Here is one idea. We can use ifelse
to replace a target value to 0
.
# Create an example data frame
dat <- data.frame(a = c("1", "5", "3", "N/A"),
b = c("a", "b", "c", "d"))
# Replace N/A with 0 in column a
dat$a <- ifelse(dat$a %in% "N/A", "0", dat$a)
# Convert column a to numeric
dat$a <- as.numeric(dat$a)
# See the results
dat
# a b
# 1 1 a
# 2 5 b
# 3 3 c
# 4 0 d

www
- 38,575
- 12
- 48
- 84
0
I edited my response to this question:
library(dplyr)
library(readr)
library(stringr)
df <- tibble(x = c("1", "2", "N/A"), y = c("4", "N/A", "5"))
df %>%
mutate(across(x:y, ~ str_replace(.x, "N/A", "0")),
across(x:y, ~ parse_double(.x)))
# A tibble: 3 x 2
x y
<dbl> <dbl>
1 1 4
2 2 0
3 0 5

Anoushiravan R
- 21,622
- 3
- 18
- 41
-
1The question specifies that the string "N/A" should be replaced by 0, not NA. – neilfws Apr 06 '21 at 01:57
-
Oh sorry, that was a huge mistake. Thank you very much dear Mr. @neilfws for letting me know. – Anoushiravan R Apr 06 '21 at 11:17