r - r - 将浮点数舍入到距离截断内最近的整数

我有一个data.frame,其中一列指定ID,另一列有数字值,在这些数值列中,有一个整数的分数和一个浮点数的分数:


set.seed(1)


df <- data.frame(id = paste0("id_",sample(LETTERS,100,replace=T)),


 var_1 = c(as.integer(runif(80,0,3)),runif(20,0,2))[permute::shuffle(100)],


 var_2 = c(as.integer(runif(90,0,3)),runif(10,0,2))[permute::shuffle(100)],


 var_3 = c(as.integer(runif(70,0,3)),runif(30,0,2))[permute::shuffle(100)])



现在我有了这个:


df[,-1] <- do.call(cbind,lapply(colnames(df)[-1], function(i){


 dists <- ceiling(df[,i])-df[,i]


 idx <- which(dists > 0.5)


 if(length(idx) > 0) dists[idx] <- dists[idx]-1


 idx <- which(abs(dists) > 0.1)


 if(length(idx) > 0) dists[idx] <- NA


 return(df[,i]+dists)


}))



但是想知道有没有更快/更优雅的?

时间:

通过创建逻辑matrix,也可以在没有循环的情况下完成


dists <- ceiling(df[-1]) - df[-1]


i1 <- dists > 0.5


dists[i1] <- dists[i1] -1


i2 <- abs(dists) > 0.1


dists[i2] <- NA


df[-1] <- df[-1] + dists



...