Search code examples
rdataframereplacetibble

Cleaner way to replace values in a tibble list


I’m trying to come up with a cleaner way (less typing) to replace values in lists in a large tibble. From looking around online, it seems common to use subsetting rather than $ to replace values, like this:

mtcars["cyl"][mtcars["cyl"] == 4] <- 6

I would like to do this with less code because I need to do it manually (with different replacements) 2-3 times for over 200 columns in this tibble. My tibble name and column names are also pretty long, making this cumbersome.

I tried to write my own function that did the same thing, but I couldn’t get it to work:

val_set <- function(df, column, old_value, replace) {
  df[column][df[column] == old_value] <- replace
}

Then I learned about the replace function, but I can only make it work with $ and not []. And when I go to check on the change with View(), the values remain unchanged. Does that have to do with using $ vs []?

replace(mtcars$cyl, mtcars$cyl == 4, 6)

What is the safest and fastest way to do this?


Solution

  • It is just that we need to assign it back to the object

    val_set <- function(df, column, old_value, replace) {
      df[[column]][df[[column]] == old_value] <- replace
      df
    }
    mtcars <- val_set(mtcars, 'cyl', 4, 6)
    

    Now, check the 'mtcars' 'cyl' column

    mtcars$cyl
     [1] 6 6 6 6 8 6 8 6 6 6 6 8 8 8 8 8 8 6 6 6 6 8 8 8 8 6 6 6 8 6 8 6