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 columnmpg
mpg = ifelse(...)
- set values ofmpg
depending on a conditionifelse(cyl == 8, 1, cyl)
- if the value ofcyl
is equal to8
, return1
; otherwise return the value ofcyl
- together:
mutate(mpg = ifelse(cyl == 8, 1, cyl)
- set the values ofmpg
to1
in rows where thecyl
-column is equal to8
; in all other cells, leavempg
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).