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

如何在RStudio的大数据框中计算基因型及单数字的频率百分比?

解决方案

1. 提取目标列并计算统计量

假设你的数据框名为df,先筛选出第4到124列的基因型数据:

geno_cols <- df[, 4:124]

计算基因型频率百分比

遍历每一列,统计每种基因型的占比(保留1位小数):

geno_freq <- apply(geno_cols, 2, function(col) {
  tbl <- table(col)
  round(prop.table(tbl) * 100, 1)
})
# 转置为数据框,行对应基因型列,列对应基因型类型
geno_freq_df <- as.data.frame(t(geno_freq))

计算单个等位基因(0/1)的频率百分比

拆分每个基因型的两个等位基因,统计0和1的占比:

library(stringr)

allele_freq <- apply(geno_cols, 2, function(col) {
  # 拆分基因型为单个字符,去除分隔符"|"
  alleles <- str_split(col, "\\|", simplify = TRUE) %>% as.vector()
  tbl <- table(alleles)
  # 处理某列无0或无1的情况,确保结果包含两个等位基因的占比
  c(`0` = ifelse("0" %in% names(tbl), round(prop.table(tbl)["0"]*100, 1), 0),
    `1` = ifelse("1" %in% names(tbl), round(prop.table(tbl)["1"]*100, 1), 0))
})
# 转置为数据框
allele_freq_df <- as.data.frame(t(allele_freq))

2. 合并统计结果

把基因型频率和等位基因频率整合为一个完整的统计表格:

final_stats <- cbind(geno_freq_df, allele_freq_df)
# 保留原基因型列名作为行标识
rownames(final_stats) <- colnames(geno_cols)

3. (可选)将统计结果添加到原数据框末尾

如果需要把统计行追加到原数据框中:

# 转置统计表格,让每一行对应原数据框的列
stats_rows <- t(final_stats)
# 给统计行命名,区分基因型和等位基因统计
rownames(stats_rows) <- paste0(
  rep(c("基因型频率_", "等位基因频率_"), c(ncol(geno_freq_df), ncol(allele_freq_df))),
  colnames(final_stats)
)
# 追加到原数据框
df_with_stats <- rbind(df, as.data.frame(stats_rows))

4. (可选)用gtsummary生成可视化统计表格

如果需要美观的输出表格,可以用gtsummary处理:

library(gtsummary)
library(dplyr)

final_stats %>%
  rownames_to_column(var = "基因型列") %>%
  tbl_summary(by = 基因型列, missing = "no") %>%
  modify_header(all_stat_cols() ~ "**频率百分比**") %>%
  bold_labels()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:30:25