我有507个表(pattern =“human”) 在每个表格中,有许多列我想通过学生的t检验进行比较。在我学习'函数'之前,我在我的data.frame中初始化了16列,并且复制了很多代码,用于16次比较。 :(但我想通过使用函数来简化代码。
问:我是否需要某种计数器或使用'cbind'?或者什么? 有什么建议吗?
files_to_test <- list.files(pattern="human")
num_files <- length(files_to_test)
## Function: Calculate t-test P-values ##
g<-function(compareA,compareB) {
for (i in 1:num_files){
temp <- read.table(files_to_test[i], header=TRUE, sep="\t")
## Obtain Columns To Compare ##
colA <- temp[compareA]
colB <- temp[compareB]
ttr <- t.test(colA, colB, var.equal=TRUE)
tt_pvalues[i,1] <- ttr$p.value
}
tag <- paste(compareA, compareB, sep="_Vs_")
tt_titles <- data.frame(tag,tt_titles) # Here is my problem.
ALL_pvalues <- data.frame(tt_pvalues, ALL_pvalues) # Here is my problem.
}
## Comparison 1
compareA <-"log_b"
compareB <-"log_b_rich"
g(compareA,compareB)
## Comparison 2
compareA <-"fc_Etoh_CDT_tot_poly"
compareB <-"log_b_rich"
g(compareA,compareB)
source.file.name, tag[i], tag[j], ...
files_to_test[1], #, #, ...
files_to_test[2], #, #, ...
我想要做的是用cbind或data.frame将早期ttest数据附加或折叠我的新列表ttest数据。我不确定。
答案 0 :(得分:0)
没有可以使用的数据......有这样的东西吗?
g <- function(compareA, compareB) {
tt_pvalues <- NULL
for (i in 1:num_files){
temp <- read.table(files_to_test[i], header=TRUE, sep="\t")
colA <- temp[compareA]
colB <- temp[compareB]
ttr <- t.test(colA, colB, var.equal=TRUE)
tt_pvalues[i] <- ttr$p.value
}
out <- data.frame(files = files_to_test, pval = tt_pvalues)
return(out)
}
答案 1 :(得分:0)
我认为你需要在循环中移动标记操作:
# Pre-allocate tag[i] outside the loop
tag <- vector("character", length=num.files)
g<-function(compareA,compareB) {
for (i in 1:num_files){
temp <- read.table(files_to_test[i], header=TRUE, sep="\t")
## Obtain Columns To Compare ##
colA <- temp[compareA]
colB <- temp[compareB]
ttr <- t.test(colA, colB, var.equal=TRUE)
tt_pvalues[i,1] <- ttr$p.value
tag[i] <- paste(compareA, i, "Vs" compareB, i sep="_")
}
tt_titles <- data.frame(tag, tt_titles) # Here is my problem.
ALL_pvalues <- data.frame(tt_pvalues, ALL_pvalues) # Here is my problem.
}