2016-02-12 144 views
-1

我有以下用R編寫的代碼片段,我應該放在for循環中。我是R新手,所以我需要你的幫助。更改變量並將輸出保存在for循環中R

我分解的代碼:

進口lmerTest包

library(lmerTest) 

負載的表(這應該是外面的for循環

table = read.csv("path/namefile.csv") 
table_data = table 
table_data[table_data == "<undefined>"] <- NA 
na_rows <- is.na(table_data[,4]) 
table_data_sub <- table_data[!na_rows,] 

我計算模型,這應該是for循環和STAGE1每次都會改變,特別是它應該是STAGE1,STAGE2,...,直到STAGE13 所有這些變量都是t ALBE table_data_sub的for循環

TNST.model <- lmer(STAGE1 ~ Patient_type+Gender+Age+(1|Subject),data=table_data,REML=FALSE) 

我計算最小二乘裝置

TNST.model_ls <-lsmeans(TNST.model) 
difflsmeans_TNST<-difflsmeans(TNST.model, test.effs=NULL) 

我保存的輸出在2個文件應該相應地改變名稱到STAGE

開始

out_file <- file("/path/STAGE1_diffmean.csv", open="a") #creates a file in append mode 
for (i in seq_along(difflsmeans_TNST)){ 
    write.table(names(difflsmeans_TNST)[i], file=out_file, sep=",", dec=".", 
       quote=FALSE, col.names=FALSE, row.names=FALSE) #writes the name of the list elements ("A", "B", etc) 
    write.table(difflsmeans_TNST[[i]], file=out_file, sep=",", dec=".", quote=FALSE, 
       col.names=NA, row.names=TRUE) #writes the data.frames 
} 
close(out_file) #close connection to file.csv 

out_file <- file("/path/STAGE1_leastmean.csv", open="a") #creates a file in append mode 
for (i in seq_along(TNST.model_ls)){ 
    write.table(names(TNST.model_ls)[i], file=out_file, sep=",", dec=".", 
       quote=FALSE, col.names=FALSE, row.names=FALSE) #writes the name of the list elements ("A", "B", etc) 
    write.table(TNST.model_ls[[i]], file=out_file, sep=",", dec=".", quote=FALSE, 
       col.names=NA, row.names=TRUE) #writes the data.frames 
} 
close(out_file) #close connection to file.csv 

for循環結束

回答

0

這是一個容易的。

要迭代矩陣/數據幀的列(或行),只需使用apply。將循環的邏輯放入一個函數(獲取一行/一列),然後指出是否要遍歷行或列。例如:

data(cars) 

result <- apply(cars, 2, mean) 

爲了計算cars每一列的平均值。鍵入?apply以獲取有關該方法的更多信息。迭代列表,數組等等的變化。