简体   繁体   English

为什么 R 格式 function 在 dataframe 中不能按预期工作?

[英]Why does R format function not work as expected in dataframe?

The format() function is not working as expected within the dataframe using dpylr and mutate(). format() function 在 dataframe 中使用 dpylr 和 mutate() 未按预期工作。 I was attempting to edit values to insert into text for automated reporting.我试图编辑值以插入文本以进行自动报告。 The nsmall parameter for the format() function appears to come from the first row only rather than the relevant row. format() function 的 nsmall 参数似乎仅来自第一行,而不是相关行。 What am I missing?我错过了什么?

df <- data.frame (Value  = c(10/3, 10/9, 1/3, 5/4),
                  DataType = c("Num","Num","Percent","Percent"),
                  Decimals = c(3,1,0,1))
df <- df %>%
  mutate(String = format(round(Value, digits=Decimals), nsmall=Decimals),
         Output = if_else(DataType == "Num", String, paste0(String," %")))
df

Result:结果:

> df
      Value DataType Decimals String  Output
1 3.3333333      Num        3  3.333   3.333
2 1.1111111      Num        1  1.100   1.100
3 0.3333333  Percent        0  0.000 0.000 %
4 1.2500000  Percent        1  1.200 1.200 %

Expected result:预期结果:

> df
      Value DataType Decimals String  Output
1 3.3333333      Num        3  3.333   3.333
2 1.1111111      Num        1  1.1     1.1
3 0.3333333  Percent        0  0       0 %
4 1.2500000  Percent        1  1.2     1.2 %
df <- df %>%
  rowwise() %>%
  mutate(String = format(round(Value, digits=Decimals), nsmall=Decimals),
         Output = if_else(DataType == "Num", String, paste0(String," %")))

rowwise() makes everything go a row at a time. rowwise()使所有 go 一次成为一行。 There may be a vectorised way to do what you want, but this is a simple approach.可能有一种矢量化的方式来做你想做的事,但这是一种简单的方法。

> df
# A tibble: 4 × 5
# Rowwise: 
  Value DataType Decimals String Output
  <dbl> <chr>       <dbl> <chr>  <chr> 
1 3.33  Num             3 3.333  3.333 
2 1.11  Num             1 1.1    1.1   
3 0.333 Percent         0 0      0 %   
4 1.25  Percent         1 1.2    1.2 % 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM