我的数据框中有两个逻辑向量:
df <- data.frame(log1 = c(FALSE, FALSE, TRUE, FALSE, TRUE), log2 = c(TRUE, FALSE, FALSE, FALSE, TRUE))
我想将这两栏结合起来制作第三栏。但这个新列不应只包含逻辑值。相反,它应该为第三列分配三个值之一 - “高”、“异常值”或“正常”。 “高”优先,因此第 5 行的第三列应显示“高”而不是“异常值”。
我想可以使用
if
和 else
来做到这一点,但我无法使用以下代码使其工作:
df$new <- NA
if(df$log1 == TRUE){
df$new <- "high"
} else if(df$log2 == TRUE) {
df$new <- "outlier"
} else {
df$new <- "normal"
}
有人可以帮忙吗?
这都是关于
ifelse
及其衍生物。
ifelse(df$log1, "high", ifelse(df$log1, "outlier", "normal"))
# [1] "normal" "normal" "high" "normal" "high"
我们可以嵌套
dplyr::if_else
,但嵌套通常鼓励我们使用 case_when
。
library(dplyr)
df %>%
mutate(new = case_when(log1 ~ "high", log2 ~ "outlier", TRUE ~ "normal"))
# log1 log2 new
# 1 FALSE TRUE outlier
# 2 FALSE FALSE normal
# 3 TRUE FALSE high
# 4 FALSE FALSE normal
# 5 TRUE TRUE high
同样,
fifelse
和fcase
:
df %>%
mutate(
new1 = if_else(log1, "high", if_else(log2, "outlier", "normal")),
new2 = case_when(log1 ~ "high", log2 ~ "outlier", TRUE ~ "normal")
)
# log1 log2 new1 new2
# 1 FALSE TRUE outlier outlier
# 2 FALSE FALSE normal normal
# 3 TRUE FALSE high high
# 4 FALSE FALSE normal normal
# 5 TRUE TRUE high high
同样,
fifelse
和fcase
:
library(data.table)
as.data.table(df)[, new1 := fifelse(log1, "high", fifelse(log2, "outlier", "normal"))
][, new2 := fcase(log1, "high", log2, "outlier", rep(TRUE, .N), "normal")][]
# log1 log2 new1 new2
# <lgcl> <lgcl> <char> <char>
# 1: FALSE TRUE outlier outlier
# 2: FALSE FALSE normal normal
# 3: TRUE FALSE high high
# 4: FALSE FALSE normal normal
# 5: TRUE TRUE high high
请注意,虽然上面的
dplyr::case_when
使用波形符公式,如 cond1 ~ value1, cond2 ~ value2
,但 fcase
变体使用交替参数,cond1, value1, cond2, value2, ...)
尝试不使用
if
/else
:
df$new <- "normal"
df[df$log1, ]$new <- "high"
df[!df$log1 & df$log2, ]$new <- "outlier"
log1 log2 new
1 FALSE TRUE outlier
2 FALSE FALSE normal
3 TRUE FALSE high
4 FALSE FALSE normal
5 TRUE TRUE high