gpt4 book ai didi

R- 使用列表的值作为名称将列表的列转换为不同的列(虚拟)

转载 作者:行者123 更新时间:2023-12-02 02:10:44 26 4
gpt4 key购买 nike

我有一个包含电影数据的表,在最后一列中,它包含电影所属的类别。

  movieId                              title                   category
1 Toy Story (1995) Animation|Children|Comedy
2 Jumanji (1995) Adventure|Children|Fantasy
3 Grumpier Old Men (1995) Comedy|Romance
4 Waiting to Exhale (1995) Comedy|Drama
5 Father of the Bride Part II (1995) Comedy
6 Heat (1995) Action|Crime|Thriller

我想为每个类别创建一列,如果该类别已写入该电影的列表中,则输入 1,如果没有,则输入 0。像这样的东西:

movieId title   animation   comedy  drama
1 xx 1 0 1
2 xy 1 0 0
3 yy 1 1 0

到目前为止,我仅将字符串转换为列表:

f<-function(x) {strsplit(x, split='|', fixed=TRUE)}
movies2$m<-lapply(movies2$category, f)

但我不知道剩下的该怎么做。

我想到了 Python 字典。但我不知道如何在 R 中执行此操作。

数据

df1 <- read.table(header = TRUE, stringsAsFactors = FALSE,
text = " movieId title category
1 'Toy Story (1995)' Animation|Children|Comedy
2 'Jumanji (1995)' Adventure|Children|Fantasy
3 'Grumpier Old Men (1995)' Comedy|Romance
4 'Waiting to Exhale (1995)' Comedy|Drama
5 'Father of the Bride Part II (1995)' Comedy
6 'Heat (1995)' Action|Crime|Thriller")

最佳答案

分割后我们可以使用qdapTools中的mtabulate

library(qdapTools)
cbind(df1[-3],mtabulate(strsplit(df1$category, "[|]")))
# movieId title Action Adventure Animation Children Comedy Crime Drama Fantasy Romance Thriller
#1 1 Toy Story (1995) 0 0 1 1 1 0 0 0 0 0
#2 2 Jumanji (1995) 0 1 0 1 0 0 0 1 0 0
#3 3 Grumpier Old Men (1995) 0 0 0 0 1 0 0 0 1 0
#4 4 Waiting to Exhale (1995) 0 0 0 0 1 0 1 0 0 0
#5 5 Father of the Bride Part II (1995) 0 0 0 0 1 0 0 0 0 0
#6 6 Heat (1995) 1 0 0 0 0 1 0 0 0 1
<小时/>

或者使用基础R

cbind(df1[-3], as.data.frame.matrix(table(stack(setNames(strsplit(df1$category,
"[|]"), df1$movieId))[2:1])))

关于R- 使用列表的值作为名称将列表的列转换为不同的列(虚拟),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37887512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com