这里有一些方法:
movies <- data.frame(genre_list = I(list(
c("drama", "action", "romance"),
c("crime", "drama"),
c("crime", "drama", "mystery"),
c("thriller", "indie"),
c("thriller"),
c("drama", "family"))))
更新,多年后......
您可以使用“qdapTools”中的函数mtabulate
或charMat
我的“splitstackshape”包中未导出的函数。
语法是:
library(qdapTools)
mtabulate(movies$genre_list)
# action crime drama family indie mystery romance thriller
# 1 1 0 1 0 0 0 1 0
# 2 0 1 1 0 0 0 0 0
# 3 0 1 1 0 0 1 0 0
# 4 0 0 0 0 1 0 0 1
# 5 0 0 0 0 0 0 0 1
# 6 0 0 1 1 0 0 0 0
或者
splitstackshape:::charMat(movies$genre_list, fill = 0)
# action crime drama family indie mystery romance thriller
# [1,] 1 0 1 0 0 0 1 0
# [2,] 0 1 1 0 0 0 0 0
# [3,] 0 1 1 0 0 1 0 0
# [4,] 0 0 0 0 1 0 0 1
# [5,] 0 0 0 0 0 0 0 1
# [6,] 0 0 1 1 0 0 0 0
更新:一些更直接的方法
改进的选项1:table
直接使用:
table(rep(1:nrow(movies), sapply(movies$genre_list, length)),
unlist(movies$genre_list, use.names=FALSE))
改进的选项 2:使用for
循环。
x <- unique(unlist(movies$genre_list, use.names=FALSE))
m <- matrix(0, ncol = length(x), nrow = nrow(movies), dimnames = list(NULL, x))
for (i in 1:nrow(m)) {
m[i, movies$genre_list[[i]]] <- 1
}
m
以下是旧答案
将列表转换为 s 的列表table
(进而转换为data.frame
s):
tables <- lapply(seq_along(movies$genre_list), function(x) {
temp <- as.data.frame.table(table(movies$genre_list[[x]]))
names(temp) <- c("Genre", paste("Record", x, sep = "_"))
temp
})
使用结果列表Reduce
。merge
如果我正确理解您的最终目标,这将导致您感兴趣的结果的转置形式。
merged_tables <- Reduce(function(x, y) merge(x, y, all = TRUE), tables)
merged_tables
# Genre Record_1 Record_2 Record_3 Record_4 Record_5 Record_6
# 1 action 1 NA NA NA NA NA
# 2 drama 1 1 1 NA NA 1
# 3 romance 1 NA NA NA NA NA
# 4 crime NA 1 1 NA NA NA
# 5 mystery NA NA 1 NA NA NA
# 6 indie NA NA NA 1 NA NA
# 7 thriller NA NA NA 1 1 NA
# 8 family NA NA NA NA NA 1
转置和转换NA
为0
非常简单。只需删除第一列并将其重新用作names
新列data.frame
movie_genres <- setNames(data.frame(t(merged_tables[-1])), merged_tables[[1]])
movie_genres[is.na(movie_genres)] <- 0
movie_genres