I want to change values in my username
variable but only when they meet a condition set from the variable chatforum
. For example, I want all instances of users called "Alex" from Canadian chatrooms to be relabeled as "AlexCA":
# mock dataset
library(tidyverse)
username <- c("Alex", "Alex", "Alex", "Alex")
id <- c(1001, 1002, 1003, 1001)
chatforum <- c("Canada", "U.S.", "U.K.", "Canada")
df <- cbind(username, id, chatforum)
df <- as_tibble(df)
glimpse(df)
df <- df %>% filter(chatforum=="Canada") %>%
mutate(username = replace(username, username == "Alex", "AlexCA"))
Though the code above works, I want the entire dataset returned to me, with the changes I just made. Using filter
returns a dataset with only the filtered rows, not the entire dataset.
I was advised to use if_else
or case_when()
but this also changes the username Alice
to AlexCA
, when I only want the username
"Alex" to change when chatroom == Canada
:
df <- df %>% mutate(username = if_else(chatforum=="Canada", "AlexCA", username))
Do you know how I can change the values in my username
column based on the condition that the value is Alex
and the chatroom
value is equal to Canada
?