1
votes

I'm trying to do a for loop for cleaning some consecutive variables but I cannot make it work

This is the repetitive code I want to avoid:

BD_INA$b16a1[BD_INA$b16a1=="NA"]<-"0"
BD_INA$b16a2[BD_INA$b16a2=="NA"]<-"0"

etc. It's from the columns 37 to 76 of a dataframe called BD_INA

And this is the loop i'm trying to make. The dataframe is called BD_INA, I'm just trying to substitute the "NA" (in text format) for "0"'s

bucle2 <- BD_INA %>%  for (i in 37:76(BD_INA)) {
  
  BD_INA["NA"] <- "0" 
  
}

I get this result: "Error in for (. in i) cols(37:76(BD_INA)) : 4 arguments passed to 'for' which requires 3"

1

1 Answers

0
votes

First, let's create some fake data.

df <- tibble::tribble(
  ~item, ~quantity,
  "saw",        2L,
  "saw",        4L,
  "saw",        6L,
  "hammer",        1L,
  "hammer",        NA,
  "hammer",        3L
)

Now, let's mutate across several columns. Replace with 37:76 in your case.

df %>% mutate(across(1:2, ~ifelse(is.na(.x),0,.x)))

# A tibble: 6 × 2
  item   quantity
  <chr>     <dbl>
1 saw           2
2 saw           4
3 saw           6
4 hammer        1
5 hammer        0
6 hammer        3