Apply gsub() function to dataframe


I have a data frame with "n/a" instead of "NA" and I would like to change the format over the full data frame. I tried using the map() function and the gsub() function together:

vol2 <- vol %>%
  map(gsub("n/a", "NA", vol), vol)

Obviously that syntax is a little redundant (and doesn't work), so I was wondering how I might be able to accomplish this.

Here is a subset of my data:

vol <- structure(list(SERIAL = c("166", "167", "177", "178", "179", 
"186"), STIS. = c("n/a", "n/a", "n/a", "n/a", "n/a", "n/a"), 
    Volume_m3 = c(2.35845643690293, 14.7035018488167, 3.04633956433295, 
    2.78838339154669, 4.63092748287711, 8.73365899290616)), row.names = c(NA, 
6L), class = "data.frame")

Thanks much!

please clarify; do you want to change the string "n/a" to the string "NA" or to NA_character_ (the special symbol recognised by R as data being character type, though 'missing')

Whichever one recognizes NA as a missing data point that can used in R functions, does that make sense?

vol$STIS. <- ifelse(test = vol$STIS. == "n/a",
                     yes = NA_character_,
                     no  = vol$STIS.)

Yes, this would work if I only wanted to do it in one column, but the whole dataframe has the "n/a" in both columns (I only gave you a snippet). If I wanted to do this over all columns, how would I do that? Thanks so much!

If the entire column/vector is NA then

vol$STIS.  <- vol$STIS. == NA

should do the job.

if you want to apply this treatment to every character column; use package tidyverse


fixed_vol <- vol |> mutate(across(where(is.character),
                                  .fns=\(x){if_else(condition = x == "n/a",
                                              true = NA_character_,
                                              false  = x)}))

This topic was automatically closed 21 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.