我有一個多列的資料框。我想使用以下內容創建一個名為 second.indicator 的新列:
second.indicator == -1 如果 il.count.description un.count.description > elle.count.description une.count.description
second.indicator == 0 如果 il.count.description un.count.description) == elle.count.description une.count.description
否則 second.indicator == 1
輸出是許多錯誤訊息:'second.indicator' not found / Error: unexpected '}' in "}"
il.count.descrition 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
}
uj5u.com熱心網友回復:
你不能if在里面使用-statements 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
)
uj5u.com熱心網友回復:
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)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/492173.html
