r - 将 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
为什么不这样做?我如何获得该输出?
解决方案
你想要的是两个类numeric
,integer
并且不可能在同一个向量中有两个类。
如果您仍然想要预期的输出,一种技巧是将其转换为字符
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
推荐阅读
- multithreading - std::packaged_task 和 std::function 的行为
- haskell - Combining generator for different datatypes in Quickcheck
- android - 有什么方法可以在不替换片段的情况下替换单个片段的数据?
- perl - 如何在 perl5 的格式语句中使用子例程参数?
- python - 给定一个带有空格的英文句子,我如何在 python 中估计特定单词适合该空格的概率?
- visual-studio - 在 Rider 中发布 Visual Studio 的数据库功能
- php - 显示带有两个标题的 PHP 数组中的 HTML 表
- r - 使用 R 在 for 循环中生成可重现的结果
- django - 如何创建特定的 django-model 字段,每天包含一个日期和唯一的数字?
- java - java main 方法无法编译,因为它找不到创建对象的符号