R factors levels labels # sample data originally…


annonces gay à antibes R factors, levels, labels

http://collectifclimat-paysdaix.fr/2016/07/25/1315?unapproved=19402 # sample data originally numbers # 1 = male, 2 = female people.n <- c(1, 1, 2, 2, 2) people.c <- c("male", "male", "female", "female", "female") # create a factor people.n.f <- factor(people.n, levels = c(1, 2), labels = c("male", "female")) people.c.f <- factor(people.c, levels = c("male", "female"), labels = c("male", "female")) # if you want to change the order of the levels, people.n.f <- factor(people.n, levels = c(2, 1), labels = c("female", "male")) # levels follows alphabetical order if not specified # compare this with people.c.f factor(people.c) # without specifying levels and labels # the original data will be used factor(people.n) # once used to create a factor, levels and labels are merged. # there is no labels attribute in factor. # correct levels(people.c.f) levels(people.c.f) <- c("man", "woman") people.c.f #wrong labels(people.c.f) labels(people.c.f) <- c("man", "woman")

Conclusion
By default, factor() order the levels alphabetical order or numerical order.
If you want to change the sorting order of levels manually, you need to set it when the factor is created.
It can not be changed later, even though the levels can be changed.

When creating a factor, the data and the order should be matched as the example.

factor(people.c, levels = c("male", "female"), labels = c("male", "female")) 
          ^ ---- same data ---------^    ^-------------same order -----^


Leave a Reply

Your email address will not be published. Required fields are marked *