I have a large data frame that I have some missing values in that I am trying to fill. I was trying to use the na.locf function but it is changing all of my values in the data frame into characters. My data is mortality data and the NAs are only in rows where no deaths were recorded (the first 6 columns are there but there are NAs for the rest of the columns). My df is called "City". Is there a better way in filling data? I do have some instances where data was not recorded for 20-150 weeks in other cities. Obviously I will not want the na.locf for these.
City <- na.locf(City)
It is coercing your data frame to a matrix. Instead do this:
City[] <- lapply(City, na.locf0)
or if you only want to apply it to the columns in jx (which may be a vector of integer positions, a logical vector or column names) then:
City[jx] <- lapply(City[jx], na.locf0)
or to not overwrite assign City
to City2
and then operate on City2
with te above or else use the one-liner:
City2 <- replace(City, TRUE, lapply(City, na.locf0))
or
City2 <- replace(City, jx, lapply(City[jx], na.locf0))