如何使用R按函数对特定列进行舍入?

如何使用R按函数对特定列进行舍入?,r,data.table,rounding,multiple-columns,R,Data.table,Rounding,Multiple Columns,我想对特定的列进行舍入,每列都有不同的舍入值。我尝试使用以下代码,但出现错误: roundCols <-function(repo, namcol, digiround){ repo[,"namcol"] = round(repo[,"namcol"], digits = digiround) round.staus = TRUE return(round.staus) } round.staus = FALSE ils <- config[13]$ignoreColu

我想对特定的列进行舍入,每列都有不同的舍入值。我尝试使用以下代码,但出现错误:

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
最初,我的数据:

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
,例如和


您的方法不起作用的原因:

  • 循环中缺少一个
    i
    roundCols(td,col\n,col\n rd[i])
    需要使用
    col\n[i]
  • 您的
    roundCols
    函数既不使用
    data.table
    语法(或
    set()
    :=
    )通过引用更新数据,也不
    返回更新的数据,因此任何更改都是函数的本地更改
  • 带引号的字符串“namcol”只是一个字符串。要使用参数
    namcol
    ,需要使用不带引号的参数

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

也许你可以给你的数据提供一个
dput
,使你的问题可以为其他人重现?
dput
数据在这里,
结构(list(Account=“Kishore”),Chargeable.Capacity=0.01,Expected.Capacity.in.30.days=0.0072831853027186,偏差=3.77826790758223e-11),row.names=c(NA,-1L),class=c(“data.table”,“data.frame”),.internal.selfref=)
@jay.sf这是你说的,对吗?你想四舍五入到什么?您的
dput
与您的结果相同。我想对列的值进行四舍五入。我编辑了这个问题。我想现在你可以拿到了。
for (i in 1:length(col_rnm)) {
  set(td, , col_rnm[i], round(td[, col_rnm[i], with = FALSE], col_rd[i]))
}