How to make R insert a '0' in place of missing values while reading a CSV?
<p>We have a multi-column CSV file of the following format:</p>

<pre><code>id1,id2,id3,id4
1,2,3,4
,,3,4,6
2,,3,4
</code></pre>

<p>These missing values are to be assumed as a '0' when reading the CSV column by column. The following is the script we currently have:</p>

<pre><code>data &lt;- read.csv("data.csv")

dfList &lt;- lapply(seq_along(data), function(i) {
    seasonal_per &lt;- msts(data[, i], seasonal.periods=c(24,168))
    best_model &lt;- tbats(seasonal_per)
    fcst &lt;- forecast.tbats(best_model, h=24, level=90)
    dfForec &lt;- print(fcst)
    result &lt;- cbind(0:23, dfForec[, 1])
    result$id &lt;- names(df)[i]

    return(result[c("id", "V1", "V2")])
})

finaldf &lt;- do.call(rbind, dfList)
write.csv(finaldf, file = "out.csv", row.names = FALSE)
</code></pre>

<p>This script breaks when the CSV has missing values giving the error <code>Error in tau + 1 + adj.beta + object$p : 
  non-numeric argument to binary operator</code>. How do we tell R to assume a '0' when it encounters a missing value?</p>

<p>I tried the following:</p>

<pre><code>library("forecast")
D &lt;- read.csv("data.csv",na.strings=".")
D[is.na(D)] &lt;- 0

dfList &lt;- lapply(seq_along(data), function(i) {
  seasonal_per &lt;- msts(data[, i], seasonal.periods=c(24,168))
  best_model &lt;- tbats(seasonal_per)
  fcst &lt;- forecast.tbats(best_model, h=24, level=90)
  dfForec &lt;- print(fcst)
  result &lt;- cbind(0:23, dfForec[, 1])
  result$id &lt;- names(df)[i]

  return(result[c("id", "V1", "V2")])
})

finaldf &lt;- do.call(rbind, dfList)
write.csv(finaldf, file = "out.csv", row.names = FALSE)
</code></pre>

<p>but it gives the following error:</p>

<p><code>Error in data[, i] : object of type 'closure' is not subsettable</code> </p>