You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言实现类Countif功能:按供应商、产品统计价格出现次数

解决方案

先把你的原始数据转换成可运行的R代码,方便测试:

# 构造原始数据框
df <- data.frame(
  Vendor = c(101,101,101,102,102,101,101,101,103,104,104,104),
  Product = c(1001,1001,1001,1001,1001,1002,1002,1002,1002,1002,1002,1002),
  Price = c(1.50,1.50,1.80,2.10,2.10,10.10,10.10,10.10,10.10,20.10,20.10,10.10)
)

方法一:base R 实现

用aggregate函数按Product、Vendor、Price分组统计次数,再调整列名和结构:

# 分组统计每组行数(即价格出现次数)
df2 <- aggregate(. ~ Product + Vendor + Price, data = df, FUN = length)
# 重命名计数列
colnames(df2)[4] <- "count of Price"
# 查看结果
df2

方法二:dplyr 包实现(更直观)

如果习惯tidyverse风格,用dplyr的分组统计逻辑更清晰:

# 未安装dplyr的话先运行:install.packages("dplyr")
library(dplyr)

df2 <- df %>%
  # 按指定字段分组
  group_by(Product, Vendor, Price) %>%
  # 统计每组行数
  summarise(`count of Price` = n(), .groups = "drop")

# 查看结果
df2

两种方法都能生成你需要的df2数据框,可根据自己的使用习惯选择。

内容的提问来源于stack exchange,提问作者user3214725

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 19:32:45