[英]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
返回僅包含過濾行的數據集,而不是整個數據集。
我被建議使用if_else
或case_when()
但這也會將用戶名Alice
更改為AlexCA
,當我只想在chatroom == Canada
時更改username
“Alex”:
df <- df %>% mutate(username = if_else(chatforum=="Canada", "AlexCA", username))
您知道如何根據值為Alex
且chatroom
值等於Canada
的條件更改我的username
名列中的值嗎?
對於使用case_when
或ifelse
,您可以有多個必須滿足的條件才能應用更改。 因此,如果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"
Output
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.