【问题标题】:How to change number of decimal points depending on value in a column?如何根据列中的值更改小数点数?
【发布时间】:2021-07-19 06:58:38
【问题描述】:

我想改变“结果”,使其具有与“限制”相同的小数点数。这是数据框:

Limit Result
1 1.1
1.2 1.35
1.55 1.681

例如,如果 Limit=1.2,我想将 Result 从 1.35 更新到 1.4。

我首先通过以下方式创建了“十进制”列:

mutate(Decimal = nchar(file_ext(as.character(Limit))))
Limit Result Decimal
1 1.1 0
1.2 1.35 1
1.55 1.681 2

然后我尝试使用round()函数

mutate(Result=round(Result, digits=Decimal))

但它不起作用。所有结果均以小数点后 1 位四舍五入。 任何建议将不胜感激!

【问题讨论】:

  • 除了十进制之外,您可以标记您使用的语言或技术吗?是python还是R?

标签: r decimal


【解决方案1】:

你可以试试下面的代码

transform(
    df,
    Result2 = round(Result, (Limit %% 1 != 0) * nchar(gsub(".*\\.", "", Limit)))
)

给了

  Limit Result Result2
1  1.00  1.100    1.00
2  1.20  1.350    1.40
3  1.55  1.681    1.68

【讨论】:

  • 优雅简洁。
  • 非常感谢!
【解决方案2】:

另一个选项是 tidyverse 和基础 R 的混合:

library(dplyr)

df %>%
  rowwise() %>%
  mutate(Result = case_when(
    grepl("\\.", Limit) ~ round(Result, nchar(unlist(strsplit(as.character(Limit), "\\."))[2])),
    TRUE ~ Limit
  ))

# A tibble: 3 x 3
# Rowwise: 
  Limit Result Decimal
  <dbl>  <dbl>   <int>
1  1      1          0
2  1.2    1.4        1
3  1.55   1.68       2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多