Home > Software design >  How do I overwrite values I select from a dataframe?
How do I overwrite values I select from a dataframe?

Time:09-19

For examples this does not work:

mtcars %>%
filter(cyl == 8) %>%
select(mpg) <- 1

I would like to replace all the values I selected with 1

I want to replace everything and not only selected values, so I am not sure how to use replace

CodePudding user response:

I think you're looking for

mtcars %>% mutate(mpg = ifelse(cyl == 8, 1, cyl))

To walk you through: the code tells R to

  1. mtcars - take the dataset mtcars
  2. %>% - pass it to mutate()
  3. mutate() - change values
  4. mutate(mpg = ...) - change values in the column mpg
  5. mpg = ifelse(...) - set values of mpg depending on a condition
  6. ifelse(cyl == 8, 1, cyl) - if the value of cyl is equal to 8, return 1; otherwise return the value of cyl
  7. together: mutate(mpg = ifelse(cyl == 8, 1, cyl) - set the values of mpg to 1 in rows where the cyl-column is equal to 8; in all other cells, leave mpg unaltered.

Important: this only returns the altered dataset. If you want to actually save these changes, you need to assign the result to an(other) object, e.g. like this:

mtcars_updated <- mtcars %>%
    mutate(mpg = ifelse(cyl == 8, 1, cyl))

Hope this helps!

P.S.: if you have a more complex conditional structure, ifelse isn't great. It'd be better to use case_when() (ensure to also include a condition that is TRUE ~ cyl in the end).

  • Related