Issue
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
Solution
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))
[Edit] As correctly highlighted in the comments: you can also use the %<>% operator to manipulate an object and assign the result to the initial object. For your example:
mtcars %<>%
mutate(mpg = ifelse(cyl == 8, 1, cyl))
However, this is less explicit code and discouraged in the tidyverse style guide (see section " 4.6 Assignment") [End of edit]
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).
Answered By - Ivo Answer Checked By - Willingham (sql.easybugfix Volunteer)
Post a Comment
Post a Comment