我有下表:
| 總調整 | 準確性 |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 4 | 5 |
| 1 | 3 |
并希望通過 totalAdjustments 將其分為兩組:
group1:totalAdjustments == 1(命名為:oneAdjustment)
group2:totalAdjustments >= 2(命名為:twoOrMoreAdjustments)
得到下表:
| 調整次數 | 準確性 |
|---|---|
| 一次調整 | 1 |
| 兩次或多次調整 | 2 |
| 兩次或多次調整 | 5 |
| 一次調整 | 3 |
我目前使用 fread 匯入我的 csv
結果 <- fread("data.csv")
uj5u.com熱心網友回復:
基數R
你可以使用ifelse:
ifelse(dat$totalAdjustments > 1, "twoOrMore", "one")
# [1] "one" "twoOrMore" "twoOrMore" "one"
dat$totalAdjustments <- ifelse(dat$totalAdjustments > 1, "twoOrMore", "one")
dat
# totalAdjustments accuracy
# 1 one 1
# 2 twoOrMore 2
# 3 twoOrMore 5
# 4 one 3
dplyr
library(dplyr)
dat %>%
mutate(totalAdjustments = if_else(totalAdjustments > 1, "twoOrMore", "one"))
# totalAdjustments accuracy
# 1 one 1
# 2 twoOrMore 2
# 3 twoOrMore 5
# 4 one 3
如果這被擴展為包括另一個數字,也許
大于 3 --> "tooMany"
然后我會從一個簡單的ifelse流程轉變為cut:
dat %>%
mutate(totalAdjustments = cut(totalAdjustments, c(0, 1, 3, Inf), c("one", "twoOrMore", "tooMany")))
# totalAdjustments accuracy
# 1 one 1
# 2 twoOrMore 2
# 3 tooMany 5
# 4 one 3
請注意,totalAdjustments現在是 classfactor而不是character; 差異可能沒什么,但如果您不打算上課,通常會導致意想不到的結果;在這種情況下,用 包裹它as.character,如= as.character(cut(...))。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/333116.html
上一篇:當有點 數字 ':'時替換字串
下一篇:合并兩列,優先考慮最右邊列的值
