我使用条件语句和ifelse()创建一个具有四个水平的新因子。但是,四个级别中只有三个级别正确返回。我做错了什么?
以下是我的数据:
arf <- structure(list(Location = structure(c(1L, 2L, 3L, 5L, 4L, 6L,
7L, 8L, 9L, 10L, 11L, 12L), .Label = c("FORT ERIE", "GRIMSBY",
"LINCOLN", "NIAGARA-ON-THE-LAKE", "NIAGARA FALLS", "PELHAM",
"PORT COLBORNE", "ST. CATHARINES", "THOROLD", "WAINFLEET", "WELLAND",
"WEST LINCOLN"), class = "factor"), Canal = structure(c(2L, 2L,
2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 2L), .Label = c("Canal",
"No canal"), class = "factor"), QEW = structure(c(2L, 2L, 2L,
2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L), .Label = c("No QEW", "QEW"
), class = "factor")), row.names = c(NA, -12L
), class = "data.frame")
下面是我的代码:
View(arf)
arf$QEWcanal <- "test"
arf$QEWcanal <- with(arf,
ifelse(((Canal == "Canal") & (QEW == "QEW")), "Both",
ifelse(((Canal == "No canal") & (QEW == "QEW")), "QEW only",
ifelse(((Canal == "Canal") & (QEW == "No QEW")), "Canal only",
ifelse(((Canal == "No Canal") & (QEW == "No QEW")), "Neither", "perdition")))))
View(arf)
它适用于前三种情况,但最后一种情况返回“perdition”而不是“Neither”。但是,当我用ifelse(((Canal == "No Canal") & (QEW == "No QEW")), "perdition", "Neither")))))
替换最后一行时,它可以工作。
这是令人困惑的,因为??ifelse
说使用是ifelse(test, yes, no)
。然而,当我遵循 that 用法(即上面的第一个代码块)时,我的最后一个ifelse()
语句返回“perdition”而不是“Neither”。
1条答案
按热度按时间bkhjykvo1#
对于第四个条件,您的代码显示为
No Canal
,但该列中的值显示为“No canal”(canal中的小型大写字母c
)。如果你调整它,它会起作用。此外,我建议在有多个条件时不要使用
ifelse()
。dplyr::case_when()
更适合这些场合。下面是你的代码可能的样子: