📊 R - Factors
Updated at 2017-10-13 17:57
Factors are categorical variables. Variables which take on a limited number of values.
data = c(1, 2, 2, 3, 1)
dataFactor = factor(data, labels = c("I","II","III"))
print(dataFactor)
# [1] I II II III I
# Levels: I II III
table(dataFactor)
# dataFactor
# I II III
# 2 2 1
# Chests by weight and value in axes and labeled with type.
chests <- c('gold', 'silver', 'gems', 'gold', 'gems')
weights <- c(300, 200, 100, 250, 150)
prices <- c(9000, 5000, 12000, 7500, 18000)
types <- factor(chests)
print(types)
# [1] gold silver gems gold gems
# Levels: gems gold silver
as.integer(types)
# [1] 2 3 1 2 1
levels(types)
# [1] "gems" "gold" "silver"
# Creates Rplots.pdf if ran in console.
plot(weights, prices, pch = as.integer(types))
legend("topright", levels(types), pch = 1:length(levels(types)))
Sources
- Google Developers R Programming Videos
- Try R
- Berkeley - Factors in R