r - 如何使用 R 按函数舍入特定列?
问题描述
我想对特定列进行四舍五入,每列具有不同的舍入值。我尝试使用以下代码,但它给出了一个错误:
roundCols <-function(repo, namcol, digiround){
repo[,"namcol"] = round(repo[,"namcol"], digits = digiround)
round.staus = TRUE
return(round.staus)
}
round.staus = FALSE
ils <- config[13]$ignoreColumns
ils <- gsub("\\{|\\}", "", ils)
ils <- ils %>% str_replace_all("\\&", ",")
coldrp <- unlist(strsplit(ils, "\\,"))
coldrp = gsub("[^a-zA-Z]+", ".", coldrp)
td <- fread(config[13]$save.location,stringsAsFactors = FALSE,drop=coldrp,blank.lines.skip = TRUE)
col_rnm <- c(names(td[,2]),names(td[,3])) #it has 2 column who's will be round off
col_rd <- c(2,3) #it gives digits how much rounding off required
for (i in 1:length(col_rnm)) {
round.staus = roundCols(td,col_rnm,col_rd[i])
}
td
错误是:
[.data.table
(repo,“namcol”)中的错误:未找到列:namcol
我在控制台上尝试了相同的功能,它给出了准确的结果。
预期输出:
Account Chargeable.Capacity Expected.Capacity.in.30.days Deviation
Kishore 0.01 0.007 3.778268e-11
最初我的数据:
Account Chargeable.Capacity Expected.Capacity.in.30.days Deviation
Kishore 0.007124108 0.007283185 3.778268e-11
高于给定代码的函数的预期。帮我解决这个错误。努力将不胜感激。
解决方案
改为这样做:
for (i in 1:length(col_rnm)) {
set(td, , col_rnm[i], round(td[, col_rnm[i], with = FALSE], col_rd[i]))
}
如果您查看?set
(与 相同的帮助页面?":="
)的帮助页面,您会看到它被描述为
set
是一个低开销的可循环版本:=
您会set
在这里找到许多答案,例如this one和this one。
您的方法无效的原因:
- 您
i
在循环中缺少一个:roundCols(td,col_rnm,col_rd[i])
需要使用col_rnm[i]
- 您的函数既不使用语法(或)
roundCols
通过引用更新数据,也不更新数据,因此任何更改都是函数本地的data.table
set()
:=
return
- 带引号的字符串
"namcol"
只是一个字符串。要使用参数namcol
,您需要使用不带引号的参数。
你不需要额外的功能——上面的方法set
更简单。
推荐阅读
- c# - C# 使用 CefSharp 重新打开表单
- google-play - 无法在 Google Play 商店中更改开发者网站
- c - 我的 C 程序没有以全名作为输入,还打印了荒谬的性别值
- gradle - Gradle:依赖来自 ant legacy build 的工件
- javascript - 如何在其异步函数范围之外使用变量
- typescript - Typescript:你能根据层次结构创建类型吗?
- c - 如何在结构中声明函数指针,指针指向的函数在其主体中包含该结构?
- ios - pod 安装后 Podfile.lock 散列缓存键更改,即使 pod 都是最新的 azure devops 管道
- c++ - 如何使用 CThreadPool 在后台线程上调用类方法
- docker - sudo unknown group - 需要帮助使用外部高清设置 NextCloud