为什么当我尝试使用ifelse而不是if…else来改革代码时,我得到了不同的答案。。。在R

为什么当我尝试使用ifelse而不是if…else来改革代码时,我得到了不同的答案。。。在R,r,R,我尝试将data.frame中的一些列从整数转换为数字。这段代码运行良好 test.data[] <- lapply(test.data, function(x) if(is.integer(x)) as.numeric(x) else x) test.data[]ifelse在所有情况下返回与第一个参数长度相同的结果。因此,它将返回示例中x的第一个元素。if else基于单个逻辑值(长度为1的向量或较长向量的第一个元素,带有警告)返回两个值中的一个 >x ifelse(是.intege

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

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

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

>x ifelse(是.integer(x),as.numeric(x),x)
[1] 1
>y如果其他(是.integer(y),作为.numeric(y),y)
[1] 1
>如果(真){1:10}否则{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

在您的情况下,if else是正确的操作,正如
is。integer
作用于向量并返回长度为1的逻辑值。

帮助文件将告诉您不同之处。此问题的标题不同,但解释正是您想要的
test.data[] <- lapply(test.data, function(x) ifelse(is.integer(x), as.numeric(x), x))
> 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