这是虚拟或单热编码,因此您可以将 model.matrix 与因子(或字符)向量和不带截距的公式一起使用:
~ x + 0
~ x - 1
两者都行。
dat <- read.table(header = TRUE, text = "Romance Horror Comedy Keyword
0 1 1 lol
1 0 0 love
0 0 1 lol
1 1 0 omg")
key <- c(Romance = 'love', Horror = 'omg', Comedy = 'lol')
tmp <- factor(dat$Keyword, key, names(key))
data.frame(model.matrix(~ tmp + 0))
# tmpRomance tmpHorror tmpComedy
# 1 0 0 1
# 2 1 0 0
# 3 0 0 1
# 4 0 1 0
由于key(以及因子的水平)与您的列具有相同的顺序,您也可以直接替换列:
dat[, 1:3] <- model.matrix(~ tmp + 0)
dat
# Romance Horror Comedy Keyword
# 1 0 0 1 lol
# 2 1 0 0 love
# 3 0 0 1 lol
# 4 0 1 0 omg
编辑
要将多个单词映射到一个流派,您可以使用一个列表作为关键字:
keywords <- c('lol', 'freak', 'kiss', 'ring', 'unknown', 'omg')
key <- list(
Romance = c('love', "kiss", "ring"),
Horror = c('omg', "freak", "kill"),
Comedy = 'lol'
)
lst <- stack(key)
tmp <- lst$ind[match(keywords, lst$values)]
data.frame(model.matrix(~ tmp + 0))
# tmpRomance tmpHorror tmpComedy
# 1 0 0 1
# 2 0 1 0
# 3 1 0 0
# 4 1 0 0
# 6 0 1 0
请注意,以上内容与列表中缺少的关键字不匹配(缺少第 5 行),因此为这些关键字设置单独的类别也很有用:
key <- c(key, Other = setdiff(keywords, unlist(key)))
lst <- stack(key)
tmp <- lst$ind[match(keywords, lst$values)]
data.frame(model.matrix(~ tmp + 0), keywords)
# tmpRomance tmpHorror tmpComedy tmpOther keywords
# 1 0 0 1 0 lol
# 2 0 1 0 0 freak
# 3 1 0 0 0 kiss
# 4 1 0 0 0 ring
# 5 0 0 0 1 unknown
# 6 0 1 0 0 omg
现在第 5 行显示正确
编辑2
我刚刚了解到 R >= 3.5.0 终于允许重复标签,所以不要这样做
key <- c(key, Other = setdiff(keywords, unlist(key)))
lst <- stack(key)
lst$ind[match(keywords, lst$values)]
# [1] Comedy Horror Romance Romance Other Horror
# Levels: Romance Horror Comedy Other
你可以这样做
factor(keywords, unlist(key), rep(names(key), lengths(key)))
# [1] Comedy Horror Romance Romance Other Horror
# Levels: Romance Horror Comedy Other