【问题标题】:count occurrences in column and group by id [duplicate]按id计算列和分组中的出现次数[重复]
【发布时间】:2019-05-13 14:42:35
【问题描述】:

嗨,我有下一个数据帧

  user_id webpage
       1  google
       1    bing
       2  google
       2  google
       2   yahoo

我想创建一个这样的结果数据框

user_id  google  bing  yahoo
   1       1       1     0
   2       2       0     1

它按 id 计算出现次数

我刚刚找到了一种一般计算频率的解决方案,但没有将出现次数放在自己的列中并将计数放在自己的列中。

【问题讨论】:

标签: r dplyr plyr


【解决方案1】:

这是tidyverse 解决方案。

# Create data frame
df <- read.table(text = "  user_id webpage
       1  google
       1    bing
       2  google
       2  google
       2   yahoo", header = TRUE)

# Load libraries
library(dplyr)
library(tibble)
library(tidyr)

# Count and restructure
as_tibble(table(df)) %>% spread(webpage, n)
#> # A tibble: 2 x 4
#>   user_id  bing google yahoo
#>   <chr>   <int>  <int> <int>
#> 1 1           1      1     0
#> 2 2           0      2     1

reprex package (v0.2.1) 于 2019-05-13 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多