Search code examples
rreplacedata.tablezero

Replacing zero elements with small random number in data table using R


I have the following data table. I need to replace the zero values in CPP column by small random number using R. This may be a simple task but I could not figure this out.

I tried this but giving me an error:

cty_d <- Table1[,sum(CPP==0)]
Table1[Table1 ==0] <- runif(cty_d,min=0.0001,max=0.001)

Any help is appreciated.

Table1:

    cty   year   CPP
    25    1998   0.0
    25    1999   100.2
    25    2000   25.2
    25    2001   535.0
    25    2002   0.0
    25    2003   0.0
    25    2004   75.2

Output:

    cty   year   CPP
    25    1998   0.0015
    25    1999   100.2
    25    2000   25.2
    25    2001   535.0
    25    2002   0.00014
    25    2003   0.0021
    25    2004   75.2

Solution

  • library(data.table)
    setDT(Table1)[CPP == 0, CPP := runif(.N, min=0.0001, max=0.001)]
    

    Takes Table1, subset to CPP == 0, then update CPP for that subset (:= updates by reference). .N is data.table syntax for # of observations. So 3 in your example table, since the subset of CPP == 0 has 3 rows.