【问题标题】:how to round specific columns by function using R?如何使用 R 按函数舍入特定列?
【发布时间】:2019-04-17 11:56:31
【问题描述】:

我想对特定列进行四舍五入,每列具有不同的舍入值。我尝试使用以下代码,但它给出了错误:

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

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

【问题讨论】:

  • 也许您可以提供dput 的数据,以便其他人可以重现您的问题?
  • dput 的数据在这里,structure(list(Account = "Kishore", Chargeable.Capacity = 0.01, Expected.Capacity.in.30.days = 0.0072831853027186, Deviation = 3.77826790758223e-11), row.names = c(NA, -1L), class = c("data.table", "data.frame"), .internal.selfref = &lt;pointer: 0x0000000002571ef0&gt;)
  • @jay.sf 你说的对吧?
  • 你想四舍五入到什么程度?您的dput 与您的结果相同。
  • 我想对列的值进行四舍五入。我编辑了这个问题。我想现在你可以得到它了。

标签: r data.table rounding multiple-columns


【解决方案1】:

改为这样做:

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


您的方法无效的原因:

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

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

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 2020-06-18
    • 2021-07-27
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多