【问题标题】:Add a column that sum the number of sessions per user in R [duplicate]添加一列,将 R 中每个用户的会话数相加 [重复]
【发布时间】:2016-10-01 23:20:19
【问题描述】:

我开始对移动应用程序进行数据挖掘, 我有一个看起来像这样的数据库:

数据库 用户 ID 小时日期 01 18 01.01.2016 01 18 01.01.2016 01 14 02.01.2016 01 14 03.01.2016 02 21 03.01.2016 02 08 05.01.2016 02 08 05.01.2016 03 23 05.01.2016

我想在此数据库中添加一个新列,用于汇总用户使用该应用程序的不同天数, 例如在这个数据库中,UserId#01 已经在平台上出现了三天,

预期的数据结果如下:

数据库 UserId 小时 日期 NumDates 01 18 01.01.2016 3 01 18 01.01.2016 3 01 14 02.01.2016 3 01 14 03.01.2016 3 02 21 03.01.2016 2 02 08 05.01.2016 2 02 08 05.01.2016 2 03 23 05.01.2016 1

到目前为止,我已经使用了这个命令:

数据库["NumDates"] % group_by(UserId) %>% summarise(NumDates = length(unique(Date)))

但它告诉我,当我需要 +600,000(我的数据库中的会话数)时,它只创建 5000 行(我的数据库中不同用户的数量)

如果有人可以帮助我,将不胜感激!

【问题讨论】:

    标签: r data-mining calculated-columns


    【解决方案1】:

    我们可以从data.table使用uniqueN

    library(data.table)
    setDT(Database)[, NumDates := uniqueN(Date) , by = UserId]
    Database
    #   UserId Hour       Date NumDates
    #1:      1   18 01.01.2016        3
    #2:      1   18 01.01.2016        3
    #3:      1   14 02.01.2016        3
    #4:      1   14 03.01.2016        3
    #5:      2   21 03.01.2016        2
    #6:      2    8 05.01.2016        2
    #7:      2    8 05.01.2016        2
    #8:      3   23 05.01.2016        1
    

    【讨论】:

      【解决方案2】:

      你不想要summarise,而是mutatesummarise 将通过您分组的列的不同值为您提供一行,而 mutate 将仅添加另一列并保留现有列。

      【讨论】:

        【解决方案3】:

        你可以在 dplyr 中使用 n_distict

        library("dplyr")
        database<- data.frame(UserId = c(1,1,1,1,2,2,2,3), Hour = c(18,18,14,14,21,8,8,23), Date = c("01.01.2016","01.01.2016","02.01.2016","03.01.2016","03.01.2016","05.01.2016","05.01.2016","05.01.2016"))
        database %>% group_by(userId) %>% mutate(NumDates = n_distinct(Date))
        

        结果如下

           UserId  Hour       Date NumDates
            (dbl) (dbl)     (fctr)    (int)
        1      1    18 01.01.2016        3
        2      1    18 01.01.2016        3
        3      1    14 02.01.2016        3
        4      1    14 03.01.2016        3
        5      2    21 03.01.2016        2
        6      2     8 05.01.2016        2
        7      2     8 05.01.2016        2
        8      3    23 05.01.2016        1
        

        【讨论】:

          猜你喜欢
          • 2021-03-27
          • 1970-01-01
          • 2019-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-22
          相关资源
          最近更新 更多