我这里有一个简单的课堂问题,而且我很难过。
在这个,我只应该使用ifelse
。前几行很好,但是如果我的x
是合乎逻辑的,那么该函数应该将任何TRUE
转换为单词" White"和任何FALSE
进入字"黑"。
q5 <- function (x) {
ifelse (is.numeric (x),
(div_three <- which (x %% 3 == 0)) &
(not_div_three <- which (x %% 3 != 0)) &
(x [div_three] <- (x [div_three] / 3)) &
(x [not_div_three] <- (x [not_div_three] * 2)),
ifelse (is.character (x),
stop ("Input is a character."),
ifelse (is.logical (x),
(is_true <- which (x == "TRUE")) &
(is_false <- which (x == "FALSE")) &
(x [is_true] <- "WHITE") &
(x [is_false] <- "FALSE"))))
x
}
但是,每当我运行q5 (c(TRUE, TRUE, FALSE, TRUE, TRUE))
时,我都会收到此错误:
Error in (is_true <- which(x == "TRUE")) & (is_false <- which(x == "FALSE")) & :
operations are possible only for numeric, logical or complex types
这个向量绝对合乎逻辑。我在插入单词之前尝试将其转换为字符,并尝试使用新元素,但它完全相同。 鉴于我的元素实际上是合乎逻辑的,我喜欢帮助弄清楚这个消息的含义。 谢谢!
答案 0 :(得分:3)
用此替换你的is.logical(x)代码。错误是因为在评估“白色”&amp; “FALSE”正在发生,因为在R中,任何inside()都会被返回。您可以尝试运行x&lt; - “R”和(x&lt; - “R”)来查看差异
ifelse (is.logical (x), x <- ifelse(x, "WHITE", "FALSE"))