factor(x, levels = <<see below>>, labels = <<see below>>, exclude = NA) is.factor(x) as.factor(x)
is.factor returns TRUE if x is a factor object, FALSE otherwise.
as.factor returns x, if x is a factor, factor(x) otherwise.
occupation <- c("doctor", "lawyer", "mechanic", "engineer")
income <- c(150000,100000,30000,60000)
factor(occupation)
factor(cut(income, breaks = c(0,30000,70000,200000)),
labels = c("low","mid","high"))
# make readable labels
occ <- factor(occupation,level = c("d","l","m","e"),
label = c("Doctor","Lawyer","Mechanic","Engineer"))
# turn factor into character vector
as.vector(factor)
color <- c("red", "red", "red", "green", "blue")
colors <- factor(color, c("red","green","blue"))
table(colors) # table counting occurrences of colors
# treat word "Unknown" as a missing value flag
colors <- factor(c("red","green","Unknown","blue"), exclude = "Unknown")
is.na(colors) # 3rd value will be T, the rest F