首页 > 解决方案 > 如何使用 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

高于给定代码的函数的预期。帮我解决这个错误。努力将不胜感激。

标签: rdata.tableroundingmultiple-columns

解决方案


改为这样做:

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 onethis one


您的方法无效的原因:

  • i在循环中缺少一个:roundCols(td,col_rnm,col_rd[i])需要使用col_rnm[i]
  • 您的函数既不使用语法(或)roundCols通过引用更新数据,也不更新数据,因此任何更改都是函数本地的data.tableset():=return
  • 带引号的字符串"namcol"只是一个字符串。要使用参数namcol,您需要使用不带引号的参数。

你不需要额外的功能——上面的方法set更简单。


推荐阅读