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

如何在R中统计DataFrame多列内各企业的出现次数

如何用R语言统计企业在各月份列中的出现次数?

原始数据

首先是你提供的DataFrame构建代码:

July <- c("4Life Solutions", "A plus tech", "Afriseed", "Blue Ice","Khan Bros")
August <- c("African Craft", "ATC LTD", "4Life Solutions", "Afriseed","Khan Bros")
Sep <- c("Atlas LTD", "A plus tech", "4Life Solutions", "Afriseed","Balton LTD")

Months <- data.frame(July, August, Sep)

原始DataFrame输出:

July          August             Sep
1 4Life Solutions   African Craft       Atlas LTD
2     A plus tech         ATC LTD     A plus tech
3        Afriseed 4Life Solutions 4Life Solutions
4        Blue Ice        Afriseed        Afriseed
5       Khan Bros       Khan Bros      Balton LTD

需求

生成新的DataFrame,统计每家企业在所有月份列中的出现次数,最终格式如下:

Company Count
1 4Life Solutions     3
2        Afriseed     3
3     A plus tech     2
4        Blue Ice     1
5       Khan Bros     1
6      Balton LTD     1

实现方法

方法一:基础R实现

无需额外安装包,用基础函数完成:

# 合并所有列为一维向量
all_companies <- unlist(Months)
# 统计各企业出现频次
count_table <- table(all_companies)
# 转换为DataFrame并重命名列
result_df <- as.data.frame(count_table, stringsAsFactors = FALSE)
colnames(result_df) <- c("Company", "Count")
# 按出现次数降序排序
result_df <- result_df[order(-result_df$Count), ]

# 输出结果
print(result_df)

方法二:tidyverse包实现

适合习惯tidy风格的用户,需要先安装加载tidyverse:

# 若未安装tidyverse,先执行安装
# install.packages("tidyverse")
library(tidyverse)

# 宽表转窄表 + 统计频次 + 排序
result_df <- Months %>%
  pivot_longer(cols = everything(), names_to = "Month", values_to = "Company") %>%
  count(Company, sort = TRUE, name = "Count")

# 输出结果
print(result_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 03:43:15