r - 如何查看一个键是否随时间具有相同的值
问题描述
我正在尝试查看我的用户是否为他们所有的订单订购了相同的产品。
我的数据集看起来像这样 -
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
解决方案
我们可以用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 R
与table
df1$OrderedtheSamething = df1$Users %in% names(which(rowSums(table(df1) >
0) == 1))
推荐阅读
- wcf - 使用 SvcUtil 从 WSDL 生成 WCF [ServiceContract]:找不到架构信息
- django - django bulk create with many=True,需要从外部表中的不同字段保存外键吗?
- sql - 每小时结果,即使在 SQL Server 上为 0
- math - 余数不除
- microstrategy - Microstrategy Web API 触发报表上的计划?
- python - 如何使用 ffmpeg 分割多个 mp4 视频?当前解决方案太慢
- java-8 - java8, optional.orElse() 不工作但 optional.orElseGet() 工作
- boto3 - 从 ecs ec2 实例获取自动缩放名称
- sparql - SPARQL - 查询 Getty 数据库(ULAN - 艺术家姓名的联合列表)以获取所有艺术家
- syntax - Robots.txt 中用户代理分组的正确语法:截至 2018 年,所有爬虫是否都“理解”了?