首页 > 解决方案 > 将 trunc 与 ifelse 一起使用会产生与单独使用 trunc 不同的行为

问题描述

我正在尝试更改数据框中的一列,以便将 < 10 的数字四舍五入到小数点后一位。>= 10 的数字应该被截断,小数点后的所有内容都被丢弃。

这是一些代码:

df <- tibble (
  x = c(1.2, 3.4, 6.7, 11.44, 15.9)
)

test_trunc_ifelse <- ifelse(df$x < 10, round(df$x, digits = 1), trunc(df$x))

test_trunc <- trunc(df$x)

和一些结果:

test_trunc_ifelse
[1]  1.2  3.4  6.7 11.0 15.0

test_trunc
[1]  1  3  6 11 15

我想(并且想要)ifelse输出这个:

[1]  1.2  3.4  6.7 11 15

为什么不这样做?我如何获得该输出?

标签: r

解决方案


你想要的是两个类numericinteger并且不可能在同一个向量中有两个类。

如果您仍然想要预期的输出,一种技巧是将其转换为字符

test <- as.character(ifelse(df$x < 10, round(df$x, digits = 1), trunc(df$x)))
test
#[1] "1.2" "3.4" "6.7" "11"  "15" 

但是你不能用这个进行任何数学计算。为此,您需要再次将其转换为数字或整数。

as.numeric(test)
#[1]  1.2  3.4  6.7 11.0 15.0
as.integer(test)
#[1]  1  3  6 11 15

推荐阅读