为什么当我尝试在R中使用ifelse而不是if..els..来修改代码时,我得到了不同的答案

  • 本文关键字:代码 修改 els 答案 if ifelse r
  • 更新时间 :
  • 英文 :


我尝试将data.frame中的一些列从整数转换为数字。这段代码运行良好。

test.data[] <- lapply(test.data, function(x) if(is.integer(x)) as.numeric(x) else x)

但当我用ifelse而不是if…else时…结果就是胡说八道。

test.data[] <- lapply(test.data, function(x) ifelse(is.integer(x), as.numeric(x), x))

如果…else和这里的ifelse之间的区别是什么?非常感谢。

ifelse在所有情况下都返回与第一个参数长度相同的结果。因此,它将返回示例中x的第一个元素。if else基于单个逻辑值返回两个值中的一个(长度为1的向量,或长度较长的向量的第一个元素,并带有警告)。

> x <- c(1L, 2L, 3L)
> ifelse(is.integer(x), as.numeric(x), x)
[1] 1
> y <- c(1,2,3)
> ifelse(is.integer(y), as.numeric(y), y)
[1] 1
> if (TRUE) {1:10} else {11:20}
[1]  1  2  3  4  5  6  7  8  9 10
> if (FALSE) {1:10} else {11:20}
[1] 11 12 13 14 15 16 17 18 19 20

在您的情况下,如果else是正确的操作,因为is.integer处理向量并返回长度为1的逻辑。

最新更新