在给定的数据集中,我在位置 7 处有
cash
、other
以及 cash.other
。
df <- data.frame(values = c("loan", "cash", "equity",
"other", "commercial.news", "money.news", "cash.other"))
我正在尝试返回
grepl("cash.other", tolower(values)) ~ "Cash_Other"
,但它返回的是 Cash
。
在原始数据框中,我还有
cash
、other
和 cash.other
,这就是为什么我需要将 cash.other
返回为 Cash_Other
df <- df %>%
mutate(values = case_when(
grepl("loan", tolower(values)) ~ "Lond",
grepl("cash", tolower(values)) ~ "Cash",
grepl("equity", tolower(values)) ~ "Equity",
grepl("other", tolower(values)) ~ "Other",
grepl("commercial.news", tolower(values)) ~ "Commercial_News",
grepl("money.news", tolower(values)) ~ "Money_News",
grepl("cash.other", tolower(values)) ~ "Cash_Other",
TRUE ~ as.character(values)
))
df
当情况
Cash_Other
时,我如何返回cash.other
?
values
1 Lond
2 Cash
3 Equity
4 Other
5 Commercial_News
6 Money_News
7 Cash
仅更改 grepls 的顺序似乎可行。
library(tidyverse)
df <- data.frame(values = c("loan",
"cash",
"equity",
"other",
"commercial.news",
"money.news",
"cash.other"))
df %>%
mutate(values = case_when(
grepl("loan", tolower(values)) ~ "Lond",
grepl("cash.other", tolower(values)) ~ "Cash_Other",
grepl("cash", tolower(values)) ~ "Cash", # Cash after Cash_Other
grepl("equity", tolower(values)) ~ "Equity",
grepl("other", tolower(values)) ~ "Other", # Other after Cash_Other
grepl("commercial.news", tolower(values)) ~ "Commercial_News",
grepl("money.news", tolower(values)) ~ "Money_News",
TRUE ~ as.character(values)
))
values
1 Lond
2 Cash
3 Equity
4 Other
5 Commercial_News
6 Money_News
7 Cash_Other
注意条件。