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

如何在R中统一拼写有差异的变量并实现计数?

解决R中字符串大小写/拼写不一致的计数问题

针对你遇到的sweets变量大小写、拼写不一致导致计数不准确的问题,这里提供两种实用的实现方案:

方案1:基础R自定义映射(精准控制)

适合变体数量明确、需要固定映射的场景,直接指定每个原始值对应的标准化名称:

# 原始数据
df <- data.frame(sweets = c("cookie", "CANDY", "Cookie", "cake", "IceCream", "Candy", "Chocolate", "COOKIE", "CAKE"))

# 创建映射表:键为原始变体,值为标准化名称
name_map <- c(
  "cookie" = "Cookie", "COOKIE" = "Cookie", "Cookie" = "Cookie",
  "CANDY" = "Candy", "Candy" = "Candy",
  "cake" = "Cake", "CAKE" = "Cake",
  "IceCream" = "IceCream",
  "Chocolate" = "Chocolate"
)

# 替换得到标准化列
df$sweets_standardized <- name_map[df$sweets]

# 生成计数表
count_table <- table(df$sweets_standardized)
count_table

执行后会得到和你预期一致的计数结果:

sweets_standardized
    Cake     Candy Chocolate   Cookie IceCream 
        2         2         1         3         1 

方案2:tidyverse批量处理(高效通用)

如果大部分值仅存在大小写差异,仅少数特殊拼写需要修正,用dplyr+stringr可以快速批量处理:

library(dplyr)
library(stringr)

# 原始数据
df <- data.frame(sweets = c("cookie", "CANDY", "Cookie", "cake", "IceCream", "Candy", "Chocolate", "COOKIE", "CAKE"))

# 标准化处理:先统一大小写,再修正特殊拼写
df_standardized <- df %>%
  mutate(
    sweets_standardized = str_to_title(tolower(sweets)) %>%
      str_replace("Icecream", "IceCream")
  )

# 生成计数表
count_table <- table(df_standardized$sweets_standardized)
count_table

说明

  • tolower()将所有字符串转为小写,str_to_title()将每个单词首字母大写,解决大部分大小写不一致问题
  • str_replace()用于修正特殊拼写(比如Icecream转为你需要的IceCream)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:05:33