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
mtcars- take the datasetmtcars%>%- pass it tomutate()mutate()- change valuesmutate(mpg = ...)- change values in the columnmpgmpg = ifelse(...)- set values ofmpgdepending on a conditionifelse(cyl == 8, 1, cyl)- if the value ofcylis equal to8, return1; otherwise return the value ofcyl- together:
mutate(mpg = ifelse(cyl == 8, 1, cyl)- set the values ofmpgto1in rows where thecyl-column is equal to8; in all other cells, leavempgunaltered.
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).
