在R中我想以整数格式提取数字的结束数字。但是,我的代码输出包含舍入错误。我想这是由as.integer
函数引起的,但我不知道如何解决这个问题。另请注意,我的实际数据集大约为10GB,因此速度非常重要。
library("data.table")
data<-c(72.15,72.02,72.00,71.90,71.85,71.74,72.60)
DT<-data.table(data)
DT[,end_digit:=as.integer((data*100))%%10]
data end_digit
1: 72.15 5
2: 72.02 2
3: 72.00 0
4: 71.90 0
5: 71.85 4
6: 71.74 3
7: 72.60 9
要清楚,预期的输出是:
data end_digit
1: 72.15 5
2: 72.02 2
3: 72.00 0
4: 71.90 0
5: 71.85 5
6: 71.74 4
7: 72.60 0
答案 0 :(得分:5)
使用round
,因为as.integer
会截断。
DT[,end_digit:=round(data*100)%%10]
DT
data end_digit
1: 72.15 5
2: 72.02 2
3: 72.00 0
4: 71.90 0
5: 71.85 5
6: 71.74 4
7: 72.60 0
答案 1 :(得分:1)
DT[, end_digit := round(( data * 100 )) %% 10]