library(tidyverse)
df <- tibble(col1 = c("A", "B", "C", "D"),
col2 = c(NA, NaN, Inf, 5),
col3 = c(NA, NaN, Inf, 5))
#> # A tibble: 4 x 3
#> col1 col2 col3
#> <chr> <dbl> <dbl>
#> 1 A NA NA
#> 2 B NaN NaN
#> 3 C Inf Inf
#> 4 D 5 5
I'd like to replace col2 column values NA and NaN with 0. I'm aware I could do this with the replace_na() function, but instead am trying it in the following manner... and getting this column length error.
df %>% mutate(col2 = replace(col2, is.na(.), 0))
#> Error: Column `col2` must be length 4 (the number of rows) or one, not 12
col2 is indeed four rows in length, not twelve. Is the error misleading or am I misinterpreting something? And what to do to correct it?
The problem is that the
.in your statement is referring todf(which has 12 elements), not tocol2. You need to writeis.na(col2)explicitly...Alternatively you can use
replace_na, which is designed just for this purpose...