r, stuck on converting numeric to factor with labels
I am stuck on this topic and I am new to R. I am trying to take this repetition pattern and assign levels using factor(), as.factor(), or levels() to assign levels to 1-5 such as 1 = yes, 2 =no, 3 =sometimes, 4 = almost never, 5 = almost always (these are for the purposes of this example only, I am aware that they do not make sense in terms of order). I am out of ideas. I have tried assigning the below code to a variable ex: x and making it as.factor(x) and then use:
x <- as.factor(x)
y <- factor(x, c('yes','no','sometimes','almost never', 'almost always')
#or y <- factor(a, levels = c('yes','no','sometimes','almost never', 'almost always'), ordered = TRUE)
the output always gives me a bunch of NA values. I am trying to get R to convert 1-5 to the respective values and output yes < no < sometimes ,etc... in terms of providing an intrinsic order for my values/levels
code I have for the pattern this:
rep(c(1:5),each=3,times=4)
Solution 1:
Almost had it, its labels not levels
factor(
rep(c(1:5),each=3,times=4),
levels = 1:5,
labels = c('yes','no','sometimes','almost never', 'almost always'),
ordered = TRUE
)
Edit: as Roland pointed out, including both levels and labels is safer.