This is FAQ 7.10. Others have shown how to apply this to a single column in a data frame, or to multiple columns in a data frame. But this is really treating the symptom, not curing the cause.
A better approach is to use the colClasses
argument to read.table
and related functions to tell R that the column should be numeric so that it never creates a factor and creates numeric. This will put in NA
for any values that do not convert to numeric.
Another better option is to figure out why R does not recognize the column as numeric (usually a non numeric character somewhere in that column) and fix the original data so that it is read in properly without needing to create NA
s.
Best is a combination of the last 2, make sure the data is correct before reading it in and specify colClasses
so R does not need to guess (this can speed up reading as well).