2013-03-27 23 views
0

列數不同的循環dataframes也許是一些小事,但我試圖解決這個問題:與r中

我得的數據幀,一個25,另一個爲9列。現在,我需要做的是擬合多項式方程,其中我的因變量在25列的數據框中,我的獨立變量在9列的數據框中。 目前,我將這些列組合在一起並創建了一個名爲「my.data」的數據框,因此我使用一個獨立變量在當時循環了因變量。但是,我想自動執行循環25 * 9次的功能。有沒有辦法做到這一點?

setwd("C:\\......") 

my.data <- read.table("MyData.txt", header = TRUE, sep = "\t") 


for(i in seq_along(my.data)) 
{ 

    fit1b <- lm(my.data[ ,i] ~ my.data$V1) 
    fit2b <- lm(my.data[ ,i] ~ poly(my.data$V1, 2, raw=TRUE)) 
    fit3b <- lm(my.data[ ,i] ~ poly(my.data$V1, 3, raw=TRUE)) 
    poly1 <-capture.output(summary(fit1b)) 
    poly2 <-capture.output(summary(fit2b)) 
    poly3 <-capture.output(summary(fit3b)) 


con = file(description = "MyResults.txt", open="a") 
write.table(poly1, file= con, append = TRUE, quote=F, col.names=FALSE, row.names= F) 
write.table(poly2, file= con, append = TRUE, quote=F, col.names=FALSE, row.names= F) 
write.table(poly3, file= con, append = TRUE, quote=F, col.names=FALSE, row.names= F) 
close(con) 
} 

回答

1

這是使用mapplyexpand.grid

例如一個絕好的機會。

# some dummy data 
xx <- data.frame(replicate(5, runif(50))) 
yy <- setNames(data.frame(replicate(3, runif(50))), paste0('Y',1:3)) 
# all combinations 
cs <- expand.grid(list(pred = names(xx), resp = names(yy)), stringsAsFactors= FALSE) 

# a function to do the fitting 
fitting <- function(pred, resp, dd){ 
    # fit linear model 
    ff <- reformulate(pred, resp) 
    lmf <- lm(ff, data =dd) 
    # create a formula for poly(,2) 
    ff.poly2 <- update(ff, .~poly(.,2, raw=TRUE)) 
    # and poly(,3) 
    ff.poly3 <- update(ff, .~poly(.,3, raw=TRUE)) 
    # fit these models 
    lmp2 <- lm(ff.poly2, data = dd) 
    lmp3 <- lm(ff.poly3, data = dd) 
    # return a list with these three models 
    list(linear = lmf, poly2 = lmp2, poly3 = lmp3) 
} 

biglist <- mapply('fitting', pred = as.list(cs[['pred']]), 
     resp = as.list(cs[['resp']]), 
     MoreArgs = list(dd = cbind(xx,yy)), SIMPLIFY = FALSE) 

# give this list meaningful names 

names(biglist) <- do.call(paste, c(cs, sep = ':')) 

然後,您可以提取的東西/使用一些嵌套lapply陳述

例如,所有的線性模型的總結總結的東西

lapply(lapply(biglist, `[[`,'linear'), summary) 
二次車型

lapply(lapply(biglist, `[[`,'poly2'), summary) 

如果你想從中提取信息在一個文件中,像

capture.output(lapply(biglist, function(x) lapply(x, summary)), file = 'results.txt') 

會創建一個名爲results.txt所有印有結果文件。

+0

非常感謝mnel,這工作得非常好!我在R很生鏽....非常感謝你!David – david 2013-03-28 00:45:10

+0

我想讓代碼做一件事。要以下面的方式總結輸出文件,如果它是一個列表,它不會像這樣,但我不確定我能否將它作爲一個總結。 – david 2013-03-28 01:37:52

0

有一件事我想要做,輸出摘要而不是列表,但我不確定是否可以使用你的寫作功能。有什麼方法可以獲得嗎?

呼叫: LM(式=我-Y-拉布勒〜MY-X-標籤)

殘差: 閔1Q中值最大3Q -0.35445 -0.17420 -0.10931 0.06975 0.60246

係數: 估計標準。誤差噸值Pr(> | T |)
(截距)0.7560212 0.0720984 10.49 1.24E-14 *

我-X-標籤0.0072100 0.0006597 10.93 2.68e-15 *

Signif。代碼: '' 0 '' 0.001 '' 0.01 '' 0.05 0.1 '' 1

殘餘標準誤差:0.2812 54自由度 的多個R平方:0.6887,調整R平方: 0.6829 F-statistic:1和54 DF上的119.5,p值:2.676e-15

+1

看到我編輯的答案。 – mnel 2013-03-28 01:54:40