It is common for data in text files to have variable-length sequences of 9s representing NAs. That is, the number of 9s that represent the NA depends on the number of characters in each variable. For instance:
- a 2 digit state code will have 99 representing NAs
- a 3 digit variable will have 999 representing NAs. Note that in this case 99 could be a legal (non-NA) value.
What is the best way to clean these values?
Note that, in fread, na.values=c('99','999') is not an ideal option because it will destroy the legal 99 values in 3 digit variables.
Let's say I have data.table d, and two sets of numeric columns
cols_2digit <- c('a','b')
cols_3digit <- c('c','d')
How can I replace sequences of 9s by NAs in all columns of each set at once? The number of sets is limited, so one command per set is fine.
OBS: these variable-length NA codes are reminiscent of fixed-width files (fwf), even if modern files are provided in csv (which could take a standard "999999" value for NA across columns).