Is it possible to define factor levels for values that are not present in a vector?
I'm trying to convert an integer vector (x) which doens't contain all possible values from my survey to a factor with matching labels. I want the value 3 to be labelled "Agree", but since it's the first value r comes across, it gets assigned the first level in my list of possible levels.
> x <- c(3L,3L,3L,3L,3L)
> x <- as.factor(x)
> levels(x) <- c("Strongly disagree","Disagree", "Agree", "Strongly agree")
> summary(x)
Results in: Strongly disagree: 5, while i would hope it would result in: Agree: 5
Can this be done?
It can be done, for example like this:
x <- c(3L,3L,3L,3L,3L)
factor_levels <- c("Strongly disagree","Disagree", "Agree", "Strongly agree")
x <- factor(factor_levels[x], levels = factor_levels)
summary(x)