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

R语言如何计算两列字符串每对组合的不同单词数量?

R实现两列字符串全配对不同单词数计算

你原有单个字符串对的计算逻辑可以直接复用,用R原生的outer函数做矩阵化运算即可高效得到你要的全配对结果矩阵,无需手动写循环遍历。

完整可运行代码

1. 构造示例数据

a <- data.frame(Occupation = c("Insurance broker","Phone Operator","real estate agent","child care worker"))
b <- data.frame(Job = c("Broker","Dog walker","health care coordinator"))

2. 封装差异计算函数

# 计算两个字符串的独有单词数量
count_diff <- function(s1, s2) {
  # 可选:统一转小写避免大小写导致的统计误差,不需要可以删除tolower
  words1 <- unlist(strsplit(tolower(s1), " "))
  words2 <- unlist(strsplit(tolower(s2), " "))
  # 统计s1中存在但s2中不存在的单词数,和你原始逻辑一致
  length(setdiff(words1, words2))
  # 如果要统计两个字符串总差异单词数(双方独有的总和),替换为下面的代码
  # length(union(words1, words2)) - length(intersect(words1, words2))
}

3. 生成全配对结果矩阵

# 生成4行(对应Occupation列)3列(对应Job列)的结果矩阵
res_mat <- outer(a$Occupation, b$Job, FUN = Vectorize(count_diff))
# 给矩阵添加行列名便于识别
rownames(res_mat) <- a$Occupation
colnames(res_mat) <- b$Job
# 查看结果
print(res_mat)

结果说明

运行后输出的矩阵格式如下:

Broker Dog walker health care coordinator
Insurance broker        1          2                        2
Phone Operator          2          2                        3
real estate agent       3          3                        3
child care worker       3          3                        2

如果需要3行4列的矩阵,仅需调换outer函数中X和Y的输入顺序即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:45:03