if else语句和if_else的不同行为 [英] Different behavior of if else statement and if_else

查看:112
本文介绍了if else语句和if_else的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,如果列的类型为 char factor c $ c>否则我什么都不会改变。但是这里的问题是我可以对 if else 语句执行相同的操作,但不能使用 if_else 语句
这是相同
的代码注意-我正在使用 titanic 数据集

I am trying to create a function which converts the data type of a data frame to factor if the column is of type char otherwise I am not changing anything. But the problem here is that I am able to do the same with if else statement but not using the if_else statement here is the code for the same Note - I am using the titanic data set

changetype = function(x)
  if(class(x) == "character") as.factor(x) else x
changetype2 = function(x)
  if_else(is.character(x),as.factor(x),x)
result1  = sapply(Train$Embarked, changetype)
result2  = sapply(Train$Embarked, changetype2)

result1 正常,而 result2 给我一个错误

result1 is working fine whereas result2 give me an error

Error: `false` has type 'character' not 'integer'

请帮助
谢谢

推荐答案

dplyr :: if_else 专门用来强迫您在中使用相同的类型。 true false 自变量。

dplyr::if_else is specifically written to force you to have the same type in your true and false arguments.

来自:?d plyr :: if_else


与基本ifelse()相比,此函数更加严格。它会检查
是非类型是否相同。

Compared to the base ifelse(), this function is more strict. It checks that true and false are the same type.

在您的情况下 x 是字符,因此在语句 if_else(is.character(x),as.factor(x),x)中, true 参数将是 factor (类型为 integer ),而 false 参数将为字符 if_else 不喜欢这样,因此返回:

In your case x is character, so in the statement if_else(is.character(x),as.factor(x),x) , the true parameter will be factor (type integer) , and the false parameter will be character. if_else doesn't like that and thus returns:


错误: false 具有类型'character'而不是'integer'

Error: false has type 'character' not 'integer'

此外, dplyr :: if_else base :: ifelse 打算与向量一起使用,因此在您的情况下,它们不是很好的选择。使用常规的 if else 调用,只会评估正确的条件, if_else ifelse 两者都进行评估。

Also, dplyr::if_else and base::ifelse are intended to be used with vectors, so in your case they're not good choices. With a regular if else call only the right condition will be evaluated, if_else and ifelse evaluate both.

这篇关于if else语句和if_else的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆