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

如何将R语言Data向量按字母排序并生成从1开始的分组列

解决方案

首先给出原始数据向量:

Data <- c("Chelsea", "Arsenal", "Liverpool", "Brighton", "Fulham", "Tottenham", "Newcastle", "Mancity", "Southampton", "Wolverhampton",
          "Chelsea", "Arsenal", "Liverpool", "Brighton", "Fulham", "Tottenham", "Mancity", "Chelsea", "Arsenal", "Mancity", "Liverpool", "Brighton", "Mancity",
          "Arsenal", "Liverpool", "Mancity", "Chelsea")

方法一:Base R 实现

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

# 1. 对向量按字母顺序排序
sorted_data <- sort(Data)

# 2. 生成从1开始的分组编号:匹配每个球队到唯一值的索引
group_ids <- match(sorted_data, unique(sorted_data))

# 3. 组合为数据框
result_df <- data.frame(Team = sorted_data, Group = group_ids)

# 查看结果
print(result_df)

方法二:使用dplyr(tidyverse工具链)

如果习惯tidyverse风格,可以用dplyr包简化操作,首次使用需先安装包:

# 安装dplyr(首次使用执行)
# install.packages("dplyr")

library(dplyr)

# 转换为 tibble,排序并添加分组列
result_df <- tibble(Team = Data) %>%
  arrange(Team) %>%  # 按字母排序球队
  mutate(Group = group_indices(., Team))  # 生成从1开始的分组编号

# 查看结果
print(result_df)

两种方法最终都会得到按字母排序的球队列表,每个不同球队对应一个连续递增的分组编号,同一球队的分组编号保持一致,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:03:16