我正在尝试创建一个函数,如果列的类型为 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
发布评论