【问题标题】:R group by | count distinct values grouping by another columnR 分组 |计算按另一列分组的不同值
【发布时间】:2018-11-29 21:42:38
【问题描述】:

如何计算每个页面名称的不同 visit_id 数量?

visit_id  post_pagename
1       A
1       B
1       C
1       D 
2       A
2       A
3       A
3       B

结果应该是:

post_pagename distinct_visit_ids
A     3
B     2
C     1
D     1

试过了

test_df<-data.frame(cbind(c(1,1,1,1,2,2,3,3),c("A","B","C","D","A","A","A","B")))
colnames(test_df)<-c("visit_id","post_pagename")
test_df

test_df %>%
 group_by(post_pagename) %>%
  summarize(vis_count = n_distinct(visit_id))

但这只给了我数据集中不同的 visit_id 的数量

【问题讨论】:

  • 为什么 D 没有包含在预期结果中。 “不同的数量”和“不同的数量”有什么区别
  • 苏里门,数量和数量是一样的。是的,可能有 D = 0,但对我来说没有必要
  • 如果visit_id1D有一次访问,怎么会是D == 0
  • 好的,对不起,我的错误。我会在我的问题发布中更正它

标签: r


【解决方案1】:

一种方式

test_df |>
  distinct() |>
  count(post_pagename)

#   post_pagename     n
#   <fct>         <int>
# 1 A                 3
# 2 B                 2
# 3 C                 1
# 4 D                 1

或其他

test_df |>
  group_by(post_pagename) |>
  summarise(distinct_visit_ids = n_distinct(visit_id))

# A tibble: 4 x 2
#  post_pagename distinct_visit_ids
#  <fct>                      <int>
#1 A                              3
#2 B                              2
#3 C                              1
#4 D                              1

*D has one visit, so it must be counted*

【讨论】:

  • 可能取决于版本。我的机器上安装了 dplyr 0.7.4。
  • utubun:我有 0.7.5
  • 我得到一行作为 distinct_visit_ids = 3 的结果
  • 我不知道为什么它在我和你的情况下表现不同。
  • ,..我会找到你的.,..我要getcha getcha getcha
【解决方案2】:

函数n_distinct() 将为您提供数据中不同的行数,因为您有 2 行是“2 A”,您应该只使用n(),这将计算您分组变量的次数出现。

test_df<-data.frame(cbind(c(1,1,1,1,2,2,3,3),c("A","B","C","D","A","A","A","B")))
colnames(test_df)<-c("visit_id","post_pagename")
test_df


test_df %>%
unique() %>%
group_by(post_pagename) %>%
summarize(vis_count = n())

这应该可以正常工作。

希望对你有帮助:)

【讨论】:

  • 我得到一个错误:Fehler: This function should not be called directly
  • 试试 dplyr::summarize(vis_count = n())
  • 这意味着您需要 dplyr 包中的汇总函数。您可以在此处查看更多关于此错误的信息 stackoverflow.com/questions/22801153/…
  • Giovana:我添加了:dplyr::summarize 并且没有出现错误。但结果不正确。请与我在问题帖中的结果进行比较。
  • 乔瓦娜;您的查询只计算每个页面名称元素的数量。 4xA、2xB、1xC、1xD
猜你喜欢
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多