r-在应用功能中,逻辑始终在数据整数时始终评估为false,但在整数为字符时正确评估
在R中,我试图在数据框中的列(a)上运行一个应用功能,并将结果放入新列(b)中。列(c)为整数类,由整数0-5组成。
我的代码是:
df$b <- apply(df, 1, FUN = function (x) if (x["a"] == 0) x["b"] = "a"
else if (x["a"] == 1) x["b"] = "b"
else if (x["a"] == 2) x["b"] = "c"
else if (x["a"] == 3) x["b"] = "d"
else if (x["a"] == 4) x["b"] = "e"
else x["b"] = "f")
当列A列为类整数时,所有逻辑都会失败,因此B列中的所有行分配了“ F”。但是,当我使用as.character()
将列A更改为字符类时,逻辑可以正确评估。为什么这样?
In R, I am trying to run an apply function on a column (a) in a dataframe and putting the result in a new column (b). The column (c) is of integer class and consists of integers 0 - 5.
My code is:
df$b <- apply(df, 1, FUN = function (x) if (x["a"] == 0) x["b"] = "a"
else if (x["a"] == 1) x["b"] = "b"
else if (x["a"] == 2) x["b"] = "c"
else if (x["a"] == 3) x["b"] = "d"
else if (x["a"] == 4) x["b"] = "e"
else x["b"] = "f")
When column a is of class integer, all the logicals fail so all rows in column b are assigned "f". However, when I change column a to character class using as.character()
, the logicals evaluate correctly. Why is this the case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从r docs
这个(我相信,如果我错了,请纠正我)是因为您比较中的价值是 r数字类型。您可以通过运行来验证这一点:
值的数字类型不等于值的整数类型,但是当您将其转换为字符时,R比较会自动转换值
该特定代码可以通过多种方式维修。对于您似乎正在做的事情,类似于以下功能的应用功能可能是一个更可读的解决方案:
请参阅vectorized
From the R Docs
This (I believe, please correct me if I'm wrong) is because the values you have in your comparisons are R numeric types. You can verify this by running:
The numeric type of a value is not equal to the integer type of the value, but when you convert it into a character, the R comparison automatically converts the value to a numeric for you, using the unicode values of the character vector.
This specific code can be repaired in multiple ways. For what you seem to be doing, an apply function similar to the following might be a more readable solution:
See the vectorized
ifelse
documentation