0

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)

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

It's safer to always specify also the levels when you specify labels. That makes the mapping explicit.
The code in its current state produces NA values for me; this was after you added the levels parameter.
@steveb My mistake, levels should include the current values, labels the new values.
@user2974951 It works now.
thanks everyone for your help, I really appreciate it. the book I am using to learn R, I have learned on labels but only for ylab and xlab. Just wondering why my code was giving NA rather than factors?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.