Replace NA with zeros in some columns

I have the following dataframe

structure(list(D_STA_F = c(NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_), ZFM_aux = c("S", "S", "S", "S", "S"), NFONTE201602 = c(1,
1, NA, 1, NA), NFONTE201603 = c(1, NA, NA, 1, NA)), row.names = c(NA,
-5L), class = c("tbl_df", "tbl", "data.frame"))

And I only want to replace NA with zeros in variables with name including NFONTE (not D_STA_F).

Here

my_data <- mutate_at(my_data, c("C1", "C4"), ~replace(., is.na(.), 0))

instead of "C1", "C4" how can I define the variable that include NFONTE in the name?

Or can I use if statement ou any loop?

Is this what you are trying to do?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tidyr)
my_data <- structure(list(D_STA_F = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), 
                          ZFM_aux = c("S", "S", "S", "S", "S"), 
                          NFONTE201602 = c(1, 1, NA, 1, NA), 
                          NFONTE201603 = c(1, NA, NA, 1, NA)), row.names = c(NA,-5L), 
                     class = c("tbl_df", "tbl", "data.frame"))
my_data
#> # A tibble: 5 x 4
#>   D_STA_F ZFM_aux NFONTE201602 NFONTE201603
#>     <dbl> <chr>          <dbl>        <dbl>
#> 1      NA S                  1            1
#> 2      NA S                  1           NA
#> 3      NA S                 NA           NA
#> 4      NA S                  1            1
#> 5      NA S                 NA           NA
my_data <- my_data |> mutate(across(.cols = starts_with("NFONTE"),
                                    .fns = ~replace(., is.na(.),0)))
my_data
#> # A tibble: 5 x 4
#>   D_STA_F ZFM_aux NFONTE201602 NFONTE201603
#>     <dbl> <chr>          <dbl>        <dbl>
#> 1      NA S                  1            1
#> 2      NA S                  1            0
#> 3      NA S                  0            0
#> 4      NA S                  1            1
#> 5      NA S                  0            0

Created on 2021-12-06 by the reprex package (v2.0.1)

1 Like

Thank you very much @FJCC.

That's it!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.