if else语句和if

编程入门 行业动态 更新时间:2024-10-19 16:29:12
本文介绍了if else语句和if_else的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试创建一个函数,如果列的类型为 char 否则我什么都不会改变。但是这里的问题是我可以对 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

本文发布于:2023-11-15 23:28:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598913.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!