GregRousell
GregRousell

Reputation: 1087

Factors in R - when I set the levels, one factor gets recoded to NA

I have a variable (x) with 4 levels - "Never", "1-2 times a month", "1-3 times a week" and "Everyday". When I try to order the levels using

x <- factor (x, levels=c ("Never", "1-2 times a month", "1-3 times a week", "Everyday"))

for some reason it recodes "Everyday" to NA and comes up as 0 when I calculate. I've tried putting it as the first, or second level and it does the same thing. When I tried to make dummy data, it worked fine so I can't give an example. I used the exact same code with a Likert variable and it worked fine.

Upvotes: 0

Views: 447

Answers (2)

GregRousell
GregRousell

Reputation: 1087

The problem was a trailing space in the original data file. The label was "Everyday ", not "Everyday". Using the unique (x) I was able to see where the problem was. I was only able to see the problem when I converted it to a character ran the unique(x) function.

Upvotes: 1

Scott Ritchie
Scott Ritchie

Reputation: 10553

As commentors have pointed out, it's likely because of a spelling error somewhere. We can conveniently remove this source of error completely, by reordering the levels of a factor numerically:

For example if your levels are in reverse you could write:

x <- factor(x, levels=levels(x)[c(4,3,2,1)])

Upvotes: 2

Related Questions