首页 > 解决方案 > 一次识别和更改多个值的小数位

问题描述

我有一个这样的数据集,但要大得多:

ds2
  Event                         act      me
<fct>                       <dbl>   <dbl>
1 Labour Costs YoY             2.33  0.0264
2 Unemployment Change (000's) -5.17 -0.449 
3 Unemployment Rate            8.86  0.0900
4 Jobseekers Net Change       11.3   9.57 

问题是第一个me变量应该是 2.64(所以乘以 100),而第二个需要乘以 10,第三个乘以 100,第四个需要保持不变。这样actme变量的小数相同。

有没有办法让 R 自动识别并纠正这个问题? 提前致谢。

要复制数据集:

ds2 <- structure(list(Event = structure(2:5, .Label = c("Event", "Labour Costs YoY", 
   "Unemployment Change (000's)", "Unemployment Rate", "Jobseekers Net Change"), 
     .Names = c("", "", "", ""), class = "factor"), act = c(2.33230769230769, -5.17018867924528, 
    8.86180371352785, 11.3192307692308), me = c(0.0263725490196078, 
     -0.449056603773585, 0.0899796195652174, 9.56704545454545)), row.names = c(NA, 
     -4L), class = c("tbl_df", "tbl", "data.frame"))

标签: rdecimalidentify

解决方案


如果新值应该是大约相同的小数位数,您可以计算值不同的因子的对数并使用它来转换它:

ds2$conversion = round(log(ds2$act/ds2$me,10))
ds2$me.new = ds2$me * 10**ds2$conversion

这导致data.frame:

> ds2
                        Event       act          me conversion    me.new
1            Labour Costs YoY  2.332308  0.02637255          2  2.637255
2 Unemployment Change (000's) -5.170189 -0.44905660          1 -4.490566
3           Unemployment Rate  8.861804  0.08997962          2  8.997962
4       Jobseekers Net Change 11.319231  9.56704545          0  9.567045

推荐阅读