r-在应用功能中,逻辑始终在数据整数时始终评估为false,但在整数为字符时正确评估

发布于 2025-02-13 06:45:49 字数 444 浏览 1 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

当爱已成负担 2025-02-20 06:45:49

从r docs

请注意,X == 0在所有情况下都不起作用。

这个(我相信,如果我错了,请纠正我)是因为您比较中的价值是 r数字类型。您可以通过运行来验证这一点:

# Assign an integer value to y
y = 5
 
# print the class name of variable
print(class(y))

值的数字类型不等于值的整数类型,但是当您将其转换为字符时,R比较会自动转换值

该特定代码可以通过多种方式维修。对于您似乎正在做的事情,类似于以下功能的应用功能可能是一个更可读的解决方案:

values <- c("a", "b", "c", "d", "e")
df$b <- ifelse( a > 4, "f", values[a + 1])

请参阅vectorized

From the R Docs

Note that x == 0 will not work in all cases.

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:

# Assign an integer value to y
y = 5
 
# print the class name of variable
print(class(y))

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:

values <- c("a", "b", "c", "d", "e")
df$b <- ifelse( a > 4, "f", values[a + 1])

See the vectorized ifelse documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文