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

如何合并同一变量的不同观测值生成新变量以绘制barplot或ggplot图表

解决方案

核心逻辑为:提取Activity列的第一个英文单词作为运动类别,再按类别对Count列求和即可,以下提供两种常用实现方式:

方法1:tidyverse 实现(适配后续ggplot作图需求)

# 加载依赖包
library(tidyverse)

# 构造示例数据
df <- data.frame(
  Count = c(10,22,12,10,5),
  Activity = c("Bikes for fitness reasons",
               "Runs for fitness reasons",
               "Bikes to commute to work",
               "Walks to commute to work",
               "Walks to stay healthy")
)

# 数据清洗合并
df_result <- df %>%
  # 提取Activity字段的第一个单词作为运动类别
  mutate(Activity = word(Activity, 1)) %>%
  # 按运动类别分组对Count求和
  group_by(Activity) %>%
  summarise(Count = sum(Count))

运行后输出的df_result即为你需要的汇总数据,可直接传入ggplot函数绘制条形图,示例作图代码:ggplot(df_result, aes(x=Activity, y=Count)) + geom_col()。

方法2:base R 实现

# 提取Activity字段的第一个单词作为运动类别
df$Activity <- sapply(strsplit(df$Activity, " "), function(x) x[1])
# 按运动类别聚合求和
df_result <- aggregate(Count ~ Activity, df, sum)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:45:03