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

将Tidyverse代码转换为Base R以适配旧版R环境

Base R 实现抛硬币序列统计与概率计算

1. 生成模拟数据集

用Base R生成包含学生ID和三次抛硬币结果的数据集,固定随机种子保证结果可复现:

set.seed(123)
num_students <- 100
tosses_per_student <- 3

student_data <- data.frame(
  StudentID = rep(1:num_students, each = tosses_per_student),
  TossResult = sample(c("H", "T"), num_students * tosses_per_student, replace = TRUE)
)

2. 生成每个学生的3次抛投序列

将每个学生的三次抛投结果合并为字符串序列,同时去重保留每个学生的唯一序列记录:

# 合并每个学生的三次结果为序列
student_data$Sequence <- ave(student_data$TossResult, student_data$StudentID, 
                             FUN = function(x) paste(x, collapse = ""))

# 提取学生ID与对应序列的唯一映射
student_sequences <- unique(student_data[, c("StudentID", "Sequence")])

3. 统计各序列的出现次数

统计所有学生中,不同3次抛投序列的出现频次:

sequence_counts <- as.data.frame(table(student_sequences$Sequence))
colnames(sequence_counts) <- c("Sequence", "OccurrenceCount")

4. 计算前两次结果对应的第三次抛投概率

拆分序列的前两次和第三次结果,再分组计算概率:

# 拆分前两次与第三次结果
student_sequences$FirstTwoTosses <- substr(student_sequences$Sequence, 1, 2)
student_sequences$ThirdToss <- substr(student_sequences$Sequence, 3, 3)

# 统计前两次组合下各第三次结果的出现次数
toss_counts <- aggregate(list(Count = student_sequences$ThirdToss),
                         by = list(FirstTwo = student_sequences$FirstTwoTosses, Third = student_sequences$ThirdToss),
                         FUN = length)

# 计算每组前两次结果的总次数
total_tosses <- aggregate(list(Total = toss_counts$Count),
                          by = list(FirstTwo = toss_counts$FirstTwo),
                          FUN = sum)

# 合并计算概率
third_toss_prob <- merge(toss_counts, total_tosses, by = "FirstTwo")
third_toss_prob$Probability <- third_toss_prob$Count / third_toss_prob$Total

关于原dplyr代码报错的说明

旧版本dplyr在summarise函数中要求输出的汇总列必须为长度1的标量值,若代码中错误地生成了长度大于1的列(比如直接在summarise中处理序列拼接),就会触发Column 'Sequence' must be length 1的报错。Base R的实现完全基于原生函数,不会受旧版本包的兼容性限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:45:17