根据 R 中的条件值更改变量中的值

Change values in a variable based on a conditional value in R

我想更改 username 变量中的值,但前提是它们满足变量 chatforum 设置的条件。例如,我希望将加拿大聊天室中名为“Alex”的所有用户实例重新标记为“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"))

虽然上面的代码有效,但我希望将整个数据集返回给我, 我刚刚所做的更改。使用 filter returns 仅包含过滤行的数据集,而不是整个数据集。

有人建议我使用 if_elsecase_when(),但这也会将用户名 Alice 更改为 AlexCA,而我只想要 username“ Alex" 在 chatroom == Canada:

时更改
df <- df %>% mutate(username = if_else(chatforum=="Canada", "AlexCA", username))

你知道我如何根据值为 Alex [=23] 的条件更改 username 列中的值吗=] 值等于 Canada?

对于使用 case_whenifelse,您可以有多个必须满足的条件才能应用更改。因此,如果 chatforum == "Canada" & username == "Alex",那么我们将名称更改为 AlexCA

library(tidyverse)

df %>%
  mutate(username = case_when(
    chatforum == "Canada" & username == "Alex" ~ "AlexCA",
    TRUE ~ username
  ))

或以 R 为基数:

df[df$chatforum == "Canada" & df$username == "Alex",]$username <- "AlexCA"

输出

  username id    chatforum
  <chr>    <chr> <chr>    
1 AlexCA   1001  Canada   
2 Alex     1002  U.S.     
3 Alex     1003  U.K.     
4 AlexCA   1001  Canada  

但是如果您需要为很多国家/地区执行此操作,那么您可能需要创建一个键或添加一个包含所需缩写的新列。例如,您可以这样做,我们从 chatforum 创建一个缩写,然后将其与 username.

组合
df %>%
  mutate(abrv = toupper(substr(str_replace_all(chatforum, "[[:punct:]]", ""), 1, 2))) %>%
  unite(username, c(username, abrv), sep = "")

#  username id    chatforum
#  <chr>    <chr> <chr>    
#1 AlexCA   1001  Canada   
#2 AlexUS   1002  U.S.     
#3 AlexUK   1003  U.K.     
#4 AlexCA   1001  Canada   

或者在创建缩写列后不合并,您仍然可以在某些条件下使用 case_when

df %>%
  mutate(abrv = toupper(substr(str_replace_all(chatforum, "[[:punct:]]", ""), 1, 2))) %>%
  mutate(username = case_when(
    chatforum == "Canada" & username == "Alex" ~ paste0(username, abrv),
    TRUE ~ username
  ))

#  username id    chatforum abrv 
#  <chr>    <chr> <chr>     <chr>
#1 AlexCA   1001  Canada    CA   
#2 Alex     1002  U.S.      US   
#3 Alex     1003  U.K.      UK   
#4 AlexCA   1001  Canada    CA