【问题标题】:conditional match and count with dplyrdplyr 条件匹配和计数
【发布时间】:2018-12-04 19:14:58
【问题描述】:

想象一下,我的朋友根据我的预算向我推荐了一些汽车。对于每个预算,我想确定所有朋友推荐相同品牌的次数以及所有朋友推荐相同品牌和型号的次数。

budget <- c(rep(c("broke", "modest", "dreaming"), each = 3), rep("broke", 3))
friend <- (rep(c("mark", "mary", "monelle"), 4))
make <- c(rep("ford", 3), rep("honda", 3), "porche", rep("bmw",2), rep("bicycle", 3))
model <- c(rep("fiesta", 3), rep("civic", 2), "tacoma", "911", "i3", "Z4", rep("used", 3))

df <- data.frame(budget, friend, make, model)

     budget  friend    make  model
1     broke    mark    ford fiesta
2     broke    mary    ford fiesta
3     broke monelle    ford fiesta
4    modest    mark   honda  civic
5    modest    mary   honda  civic
6    modest monelle   honda tacoma
7  dreaming    mark  porche    911
8  dreaming    mary     bmw     i3
9  dreaming monelle     bmw     Z4
10    broke    mark bicycle   used
11    broke    mary bicycle   used
12    broke monelle bicycle   used

期望的输出 -

budget matchMake matchMake+Model
broke      2     2 
modest     1     0
dreaming   0     0

【问题讨论】:

  • 为更新的示例添加所需的输出。
  • 希望这有意义吗?感谢您的帮助!
  • 您的 reprex 输入未遵循您的预期结果 - 如果您正在寻找更多答案,请确保您的 reprex 从头到尾都有意义。至于问题,看dplyr::count
  • 您的问题含糊不清。您是什么意思“我的朋友告诉我购买同一辆车的频率”?如果有人告诉您一次购买相同的品牌,那是 0 还是 1?如果他们告诉你两次,是 1 还是 2?

标签: r dplyr match


【解决方案1】:

这是dplyr 的一种方式。

df %>% 
  spread(friend, model) %>% 
  mutate(
    matchMake = apply(.[3:5], 1, function(x) !anyNA(x)),
    matchMake_Model = apply(.[3:5], 1, function(x) all(x[1] == x))
  ) %>% 
  group_by(budget) %>% 
  summarise(
    matchMake = sum(matchMake, na.rm = T),
    matchMake_Model = sum(matchMake_Model, na.rm = T)
  ) 

# A tibble: 3 x 3
  budget   matchMake matchMake_Model
  <fct>        <int>           <int>
1 broke            2               2
2 dreaming         0               0
3 modest           1               0

【讨论】:

  • 非常有帮助。我想要数字是因为我们可以想象朋友为每种预算类型推荐 > 1 辆汽车的场景。然后我试图计算频率,而不是每个预算的 T/F……我更新了问题以扩展 reprex:
【解决方案2】:

使用 plyr 的 split-apply-combine(根据变量“预算”拆分)并使用 count 测试指定相同品牌或品牌/型号的次数

ddply(df, .(budget), function(df_budget) 
      c(matchMake = sum(count(df_budget, "make")$freq > 1), 
        matchMakeModel = sum(count(df_budget, c("make", "model"))$freq > 1)))

【讨论】:

    猜你喜欢
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多