[英]Filter for two conditions in R and combine in one data table
我有下表:
总调整 | 准确性 |
---|---|
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")
您可以ifelse
使用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
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
现在是 class factor
而不是character
; 差异可能没什么,但如果您不打算上课,通常会导致意想不到的结果; 在这种情况下,用as.character
包裹它,如= as.character(cut(...))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.