1

I want to round off specific columns with each column have different rounding values. I tried with the following code but it gives an error:

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

error is :

Error in [.data.table(repo, , "namcol") : column(s) not found: namcol

I tried the same given in function on a console which gives an exact result.

Expected Output:

Account    Chargeable.Capacity   Expected.Capacity.in.30.days    Deviation
Kishore                0.01                 0.007              3.778268e-11

Initially My data :

Account Chargeable.Capacity Expected.Capacity.in.30.days    Deviation
Kishore         0.007124108         0.007283185           3.778268e-11

above what is expected from the function given the code. Help me to solve that error. The effort will be appreciated.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Bhavneet sharma
  • 337
  • 5
  • 16

1 Answers1

2

Do this instead:

for (i in 1:length(col_rnm)) {
  set(td, , col_rnm[i], round(td[, col_rnm[i], with = FALSE], col_rd[i]))
}

If you look at the help page for ?set (same help page as ?":="), you'll see it described as

set is a low-overhead loop-able version of :=

You'll find set used in many answers here, such as this one and this one.


Reasons your approach didn't work:

  • You're missing an i in your loop: roundCols(td,col_rnm,col_rd[i]) needs to use col_rnm[i]
  • Your roundCols function neither updates the data by reference using data.table syntax (either set() or :=), nor does it return the updated data, so any changes are local to the function
  • The string "namcol" with quotes is just a string. To use the argument namcol, you need to use it without quotes.

You don't need an extra function for this---the approach above with set is simpler.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294