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
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
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 dataset mtcars%>% - pass it to mutate()mutate() - change valuesmutate(mpg = ...) - change values in the column mpgmpg = ifelse(...) - set values of mpg depending on a conditionifelse(cyl == 8, 1, cyl) - if the value of cyl is equal to 8, return 1; otherwise return the value of cylmutate(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))
[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).