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

如何在R语言中基于两个表格创建type-token ratio表格?

使用tidyverse计算形符-类符比(Type-Token Ratio)表格

步骤1:加载tidyverse包并创建原始数据框

先将你提供的形符频率(token)和类符频率(type)数据转换为R数据框:

library(tidyverse)

# 形符频率表
token_df <- tibble(
  AUX = c("toss", "shoot", "launch", "throw", "pull"),
  `13` = c(0, 0, 32, 0, 0),
  `14` = c(0, 0, 15, 0, 0),
  `15` = c(0, 0, 101, 0, 2),
  `16` = c(20, 0, 153, 0, 0),
  `17` = c(47, 3, 95, 0, 0),
  `18` = c(16, 0, 40, 0, 8),
  `19` = c(38, 1, 500, 55, 0),
  `20` = c(11, 1, 500, 125, 7),
  `21` = c(28, 3, 500, 500, 81)
)

# 类符频率表
type_df <- tibble(
  AUX = c("toss", "shoot", "launch", "throw", "pull"),
  `13` = c(0, 0, 8, 0, 0),
  `14` = c(0, 0, 3, 0, 0),
  `15` = c(0, 0, 15, 0, 7),
  `16` = c(16, 0, 12, 0, 0),
  `17` = c(34, 2, 12, 0, 0),
  `18` = c(13, 0, 17, 0, 7),
  `19` = c(32, 1, 18, 44, 0),
  `20` = c(10, 1, 22, 95, 7),
  `21` = c(27, 3, 20, 215, 46)
)

步骤2:转换数据格式并计算比值

用pivot_longer将宽格式转为长格式,合并后计算形符-类符比,最后转回宽格式:

# 转换token数据为长格式
token_long <- token_df %>%
  pivot_longer(cols = -AUX, names_to = "year", values_to = "token") %>%
  mutate(year = as.character(year))

# 转换type数据为长格式
type_long <- type_df %>%
  pivot_longer(cols = -AUX, names_to = "year", values_to = "type") %>%
  mutate(year = as.character(year))

# 合并数据并计算type-token ratio
tt_ratio <- token_long %>%
  left_join(type_long, by = c("AUX", "year")) %>%
  # 处理token为0的情况,避免出现Inf/NaN
  mutate(ratio = case_when(
    token == 0 ~ 0,
    TRUE ~ type / token
  )) %>%
  # 保留两位小数
  mutate(ratio = round(ratio, 2)) %>%
  # 转回宽格式
  pivot_wider(id_cols = AUX, names_from = year, values_from = ratio)

步骤3:查看结果

运行上述代码后,tt_ratio即为目标表格,打印结果如下:

print(tt_ratio)
AUX131415161718192021
toss0.000.000.000.800.720.810.840.910.96
shoot0.000.000.000.000.670.001.001.001.00
launch0.250.200.150.080.130.430.040.040.04
throw0.000.000.000.000.000.000.800.760.43
pull0.000.001.000.000.000.880.001.000.57

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:24:55