I am trying to a factorize a variable which is basically a count of how many food species one has eaten. My code is bring out an error and I am not sure how to fix this.
Totals is continous variable with the food count
Foods$count_quintile <- factor(Foods$Totals, levels = 1:5,
labels = c("Q1", "Q2", "Q3", "Q4", "Q5"))
After I run this, count_quintile is still turning up empty.
Thoughts?
Short answer:
You need to round the Totals column data, so it fits into the bins of the factor variable you're trying to create.
Longer answer:
In your question you stated that "Totals is continous variable with the food count". Creating sample data which is continuous:
As you can see, every value is some fraction between 0 and 5, with every number having so many decimal places that it is very very unlikely for any of them to be a round number exactly.
In
factor(Foods$Totals, levels = 1:5, labels = c("Q1", "Q2", "Q3", "Q4", "Q5")), thelevels = 1:5part is saying that the input data is coded with the numbers 1 to 5; the first category is1, the second is2, third3, etc.So when it looks at the Total column data we see above, and it doesn't see any of those values, it returns NA. Then it repeats, creating a column of NAs.
To make it work, (assuming rounding the Total is appropriate for your data!) you can round to the nearest value, and then the code will work: