【问题标题】:r remove records that dont represent all groupsr 删除不代表所有组的记录
【发布时间】:2017-10-31 17:16:37
【问题描述】:

在处理原始数据后,我们得到了以下data.frame

        ItemID    GroupID mentions
1         601          3     1
2         601          4     1
3         611          3     1
4         661          3     1
5         801          3     1
6         821          3     1
6         841          1     3
6         841          2     3
6         841          3     3
6         841          4     3

我有 10000 条这样的记录,我的第一个目标是找出代表所有 4 个 GroupID 的项目。首先,我尝试通过绘图在视觉上做到这一点。

ggplot(item.stats, aes(x=ItemID, y=mentions, fill=GroupID)) + 
  geom_bar(stat='identity', position='dodge')

对于大型数据集,这看起来不是一件明智的事情。了解有多少项目代表所有组并提及提及的最佳方法是什么?

在上面的例子中,过滤后它应该只有:

        ItemID    GroupID mentions
6         841          1     3
6         841          2     3
6         841          3     3
6         841          4     3

试图获得有意义的可视化:

test.with.id <- transform(test,id=as.numeric(factor(ItemID)))
ggplot(test.with.id, aes(x=id, y=mentions, fill=GroupID)) + 
  geom_histogram(stat='identity', position='stack', binwidth = 2)

可能与此类似 How to plot multiple stacked histograms together in R?

【问题讨论】:

  • 假设你的数据在dat1:with(dat1, ave(GroupID, ItemID, FUN = function(x) length(unique(x))))
  • 这会删除所有没有所有 GroupID 的行

标签: r ggplot2 dplyr


【解决方案1】:

您可以按ItemID 分组,然后根据所有4 个组ID 是否都在GroupID 列中进行过滤:

df %>% group_by(ItemID) %>% filter(all(1:4 %in% GroupID))

# A tibble: 4 x 3
# Groups:   ItemID [1]
#  ItemID GroupID mentions
#   <int>   <int>    <int>
#1    841       1        3
#2    841       2        3
#3    841       3        3
#4    841       4        3

【讨论】:

  • 绘制这个的最好方法是什么。密度图?
  • 我不确定你想要可视化什么。 GroupIDmentions 在这里是什么意思?
  • 我试图做堆叠或闪避直方图刚刚用ggplot编辑了这个问题。提及是 Facebook 喜欢。您可以将组视为一个桶。
  • 可能是ggplot(df, aes(mentions, fill=factor(GroupID))) + geom_density(alpha = 0.2)? ItemID 似乎是太具体的信息,无法进入图表。只是一个猜测。另请参阅有关stacked histogram 的问题。
  • histogram 不需要y 美学,您可能需要geom_bar。试试ggplot(df, aes(x=ItemID, y=mentions, fill=factor(GroupID))) + geom_bar(position='stack', stat = 'identity')
猜你喜欢
  • 1970-01-01
  • 2014-12-07
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 2012-10-01
相关资源
最近更新 更多