Q:

Replace NA with 0 in R using a loop on a dataframe

I would like to run through specific columns in a dataframe and replace all NAs with 0s using a loop.
extract = read.csv("2013-09 Data extract.csv")
extract$Premium1[is.na(extract$Premium1)] <- 0
extract$Premium1

gives me the required result for Premium1 in dataframe extract, but I would like to loop through all 27 columns of premiums, so what I am trying is
extract = read.csv("2013-09 Data extract.csv")

for(i in 1:27) { 
  thispremium <- get(paste("extract$Premium", i, sep="")) 
  thispremium[is.na(thispremium)] <- 0
}

which gives
Error in get(paste("extract$Premium", i, sep = "")) : 
  object 'extract$Premium1' not found

Any idea on what is causing the error?

A:

Do you need the loop because of other requirements? Because it works just fine without one:
extract[is.na(extract)] <- 0

If you want to do the replacement for some columns only, select those columns first, perform the replacement, and substitute the columns back into the original set:
first5 <- extract[, 1 : 5]
first5[is.na(first5)] <- 0
extract[, 1 : 5] <- first5

More generally loops can (and should) be almost avoided in R – especially when manipulating data frames). Often operations vectorise automatically (like above). When they don’t, functions of the apply family can be used.

