【问题标题】:Given a series of users and movies they watched in a data frame, how can I group all the movies the user watched?给定一系列用户和他们在数据框中观看的电影,我如何对用户观看的所有电影进行分组?
【发布时间】:2020-05-04 15:31:34
【问题描述】:

所以,我有一个带有 userid 和 movieid 的数据框,其中每一行代表一个用户和他观看的电影。比如:

userid    movieid
882359    81
882359    926
882359    1349
881235    27

而我想要的是

userid     movieid
882359     c(81,926,1349)
881235     c(27)

我怎样才能做到这一点?数据库非常大(800 万行),最后我想将其转换为 binaryRatingMatrix。任何帮助表示赞赏。

【问题讨论】:

    标签: r dataframe recommender-systems


    【解决方案1】:

    你可以使用data.table:

    library(data.table)
    setDT(df)
    df[, .(films = paste(movieid, collapse = ",")), by = "userid"]
    
       userid       films
    1: 882359 81,926,1349
    2: 881235          27
    

    如果您更喜欢存储到 list 而不是字符向量中:

    df[, .(films = list(movieid)), by = "userid"]
       userid          films
    1: 882359   81, 926,1349
    2: 881235             27
    

    (看似相同的输出,但类型不一样)

    【讨论】:

    • 酷!如果您更喜欢存储列表而不是字符向量,我更新了答案。既然您对解决方案很满意,您是否介意接受它 (see here for guidelines if needed)
    【解决方案2】:

    aggregate 的选项来自base R

    aggregate(cbind(films = movieid) ~ userid, df, FUN = I)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 2021-10-23
      相关资源
      最近更新 更多