R语言 如果else()从其他两个因子向量创建新因子向量失败返回期望值

dojqjjoe  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(98)

我使用条件语句和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”。

bkhjykvo

bkhjykvo1#

对于第四个条件,您的代码显示为No Canal,但该列中的值显示为“No canal”(canal中的小型大写字母c)。如果你调整它,它会起作用。
此外,我建议在有多个条件时不要使用ifelse()dplyr::case_when()更适合这些场合。下面是你的代码可能的样子:

library(tidyverse)
  
arf |> 
  mutate(QEWcanal = case_when(
    Canal == "Canal" & QEW == "QEW" ~ "Both",
    Canal == "No canal" & QEW == "QEW" ~ "QEW only",
    Canal == "Canal" & QEW == "No QEW" ~ "Canal Only",
    Canal == "No canal" & QEW == "No QEW" ~ "Neither",
    TRUE ~ "peridition"
  ))
#>               Location    Canal    QEW   QEWcanal
#> 1            FORT ERIE No canal    QEW   QEW only
#> 2              GRIMSBY No canal    QEW   QEW only
#> 3              LINCOLN No canal    QEW   QEW only
#> 4        NIAGARA FALLS No canal    QEW   QEW only
#> 5  NIAGARA-ON-THE-LAKE No canal    QEW   QEW only
#> 6               PELHAM No canal No QEW    Neither
#> 7        PORT COLBORNE    Canal No QEW Canal Only
#> 8       ST. CATHARINES    Canal    QEW       Both
#> 9              THOROLD    Canal No QEW Canal Only
#> 10           WAINFLEET No canal No QEW    Neither
#> 11             WELLAND    Canal No QEW Canal Only
#> 12        WEST LINCOLN No canal No QEW    Neither

相关问题