我有一个多列的数据框。我想创建一个名为
second.indicator
的新列,其中包含以下内容:
second.indicator == -1 if il.count.description + un.count.description > elle.count.description + une.count.description
second.indicator == 0 if il.count.description + un.count.description) == elle.count.description + une.count.description
else second.indicator == 1
输出很多错误信息:
找不到“第二个指示器”/错误:“}”中出现意外的“}”
il.count.description elle.count.description un.count.description un.count.description
5 1 5 1
9 2 2 6
1 1 0 0
10 9 0 8
data <- data %>%
mutate(second.indicator =
if (il.count.description + un.count.description) > elle.count.description + une.count.description) {
second.indicator == -1
} else if (il.count.description + un.count.description) == (elle.count.description + une.count.description) {
second.indicator == 0
} else {
second.indicator == 1
}
您不能像这样在
if
中使用 mutate
语句(出于多种原因);相反,你可以使用 case_when
:
data <-
data %>%
mutate(second.indicator = case_when((il.count.description + un.count.description) > (elle.count.description + une.count.description) ~ -1,
(il.count.description + un.count.description) == (elle.count.description + une.count.description) ~ 0,
T ~ 1
)
df 是您的数据...
df <- structure(list(il = c(5L, 9L, 1L, 10L), elle = c(1L, 2L, 1L, 9L), un = c(5L, 2L, 0L, 0L), une = c(1L, 6L, 0L, 8L)), class = "data.frame", row.names = c(NA, 4L))
(变量名称中省略了多余的“.count.description”)
...你可以像这样避免容易出错的 if-else-hazzle:
df %>%
mutate(second_indicator = sign((elle + une) - (il + un)))