首页 > 解决方案 > 如何查看一个键是否随时间具有相同的值

问题描述

我正在尝试查看我的用户是否为他们所有的订单订购了相同的产品。

我的数据集看起来像这样 -

Users  Product Ordered  
A        Onion                
A        Onion                
A        Onion                
B        Carrots              
B        Carrots              
B        Spinach              

我想创建一个名为ordered 的新列吗?

Users  Product Ordered   Ordered the same thing?
A        Onion                Y
A        Onion                Y
A        Onion                Y
B        Carrots              N
B        Carrots              N
B        Spinach              N

标签: r

解决方案


我们可以用n_distinct

library(dplyr)
df1 %>%
  group_by(Users) %>%
  mutate(OrderedtheSamething = n_distinct(ProductOrdered)==1)

它返回一个逻辑列(比“Y/N”更可取)。但是,如果我们需要它,请将mutate步骤更改为

df1 %>%
  group_by(Users) %>%
  mutate(OrderedtheSamething = c("N", "Y")[(n_distinct(ProductOrdered)==1) +1])

类似的选项data.table将是

library(data.table)
setDT(df1)[, OrderedtheSamething := uniqueN(ProductOrdered)==1, by = Users]

base Rtable

df1$OrderedtheSamething = df1$Users %in% names(which(rowSums(table(df1) > 
                        0) == 1))

推荐阅读