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?
get("extract")[[paste0("Premium",i)]]although it looks rather tortured. Why do you need toget'extract'. Why not just:extract[[paste0("Premium",i)]]for(i in 1:27) { extract[[paste0("Premium", i)]][is.na(extract[[paste0("Premium", i)]])] <-0 }now which gives the required result.