1.输入数据:“5utr-5d做ABD中有RG4和没有RG4的TE之间的T检验.csv”
2.代码:
setwd("E:\\R\\Rscripts\\5UTR_extended_TE")
# 载入必要的库
library(tidyverse)
library(dplyr)
library(openxlsx)
# 读取数据
data <- read.csv("5utr-15d做ABD中有RG4和没有RG4的TE之间的T检验.csv", na.strings = "#N/A")
# 将所有的NA值转换为0
data <- data %>% mutate_all(~ifelse(is.na(.), 0, .))
############################################################
# 调整后的process_scores函数1,适用于le1的个数小于ge1的个数且ave-le1大于ave-ge1的情况
############################################################
process_scores <- function(df, score_name, TE_name) {
successful_seeds <- list() # 初始化一个列表来保存成功的seed值
combined_samples_list <- list() # 新增:初始化一个列表来保存符合条件的组合数据框
for (seed_val in 1:50) {
set.seed(seed_val)
ge1 <- df %>% filter(!!sym(score_name) >= 1) %>% select(!!sym(TE_name)) %>% mutate(Source = "ge1")
le1 <- df %>% filter(!!sym(score_name) < 1) %>% select(!!sym(TE_name)) %>% mutate(Source = "sample_le1")
sample_le1 <- sample_n(le1, nrow(ge1)) # 取单一样本进行比较
t_test <- t.test(ge1[[1]], sample_le1[[1]])
mean1 <- mean(ge1[[1]])
mean2 <- mean(sample_le1[[1]])
if (mean2 != mean1 && t_test$p.value <= 1) {
successful_seeds[[paste0(seed_val, "_", score_name)]] <- list(
seed = seed_val,
mean1 = mean1,
mean2 = mean2,
pvalue = t_test$p.value
)
# 新增:将符合条件的ge1和sample_le1合并到一个数据框中,并保存到列表中
combined_samples <- bind_rows(ge1, sample_le1)
combined_samples_list[[paste0(seed_val, "_", score_name)]] <- combined_samples
}
}
# 将成功的seeds信息转换为数据框
if (length(successful_seeds) > 0) {
successful_seeds_df <- bind_rows(successful_seeds, .id = "seed_score") %>% mutate(Comparison = seed_score)
} else {
successful_seeds_df <- tibble(Comparison = character(), mean1 = numeric(), mean2 = numeric(), pvalue = numeric())
}
# 新增:将combined_samples_list中的数据框合并或以其他形式输出
combined_samples_output <- if (length(combined_samples_list) > 0) {
# 例如,这里我们简单地将所有符合条件的数据框合并
bind_rows(combined_samples_list)
} else {
# 如果没有符合条件的,则返回空数据框
tibble()
}
return(list(successful_seeds = successful_seeds_df, combined_samples = combined_samples_output))
}
# 对AScore5d进行处理示例
results_AScore5d <- process_scores(data, "AScore5d", "ATe5d")
results_BScore5d <- process_scores(data, "BScore5d", "BTe5d")
results_DScore5d <- process_scores(data, "DScore5d", "DTe5d")
results_AScore5d_successful_seeds <- as.data.frame(results_AScore5d$successful_seeds)
results_BScore5d_successful_seeds <- as.data.frame(results_BScore5d$successful_seeds)
results_DScore5d_successful_seeds <- as.data.frame(results_DScore5d$successful_seeds)
# 打印出符合条件的successful_seeds结果进行检查
bind_results_AScore5d_successful_seeds<-cbind(results_AScore5d_successful_seeds,results_BScore5d_successful_seeds,results_DScore5d_successful_seeds)
write.xlsx(bind_results_AScore5d_successful_seeds, file = "5utr_bind_results_ABDScore15d_successful_seeds.xlsx")
3.输出结果:“5utr_bind_results_ABDScore5d_successful_seeds.xlsx”