In a dataset of 589 rows there are around 50 entries who miss a variable and are assigned the NA value, but I know which value that should have ("Brussel Hoofstedelijk Gewest" is the exact string value it should have) so I want to give those 50 entries that string value and not change anything for the rest of the rows. I have search the internet high and low for this answer but I can't seem to find it, most problems people seem to have is with numerical values and NA and not with string values. I use Rstudio and mainly dplyr, tidy and ggplot2, this is an assignment for a introductory course on R so I am trying to learn it any help would be welcome :).
Asked
Active
Viewed 695 times
0
-
1`vec[is.na(vec)] = "some new value"`. If you are using it in a `dplyr` pipe, then `mutate(vec = if_else(is.na(vec), "some new value", vec))` – r2evans Mar 05 '21 at 14:09
-
1[See here](https://stackoverflow.com/q/5963269/5325862) on making a reproducible example that is easier for folks to help with. Replacing an NA value shouldn't work any differently for strings from how it works for numbers – camille Mar 05 '21 at 14:09
-
Replacing a `NA` in a numeric vector uses the same exact methods as replacing a `NA` in a string vector. There is no difference in the method. – r2evans Mar 05 '21 at 14:10
-
1One note is that if your vector is a factor (in R, what looks like a character vector may actually be a factor vector), @r2evans method will not work. You will get the warning `invalid factor level, NA generated`. See https://stackoverflow.com/questions/39126537/replace-na-in-a-factor-column – qdread Mar 05 '21 at 14:35
1 Answers
2
Have you tried:
My_df <- my_df %>%
mutate(column_of_interest=replace_na(column_of_interest, "Brussel Hoofstedelijk Gewest"))
?

Erich Zann
- 44
- 3