与r中

与r中

问题描述:

列数不同的循环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) 
} 

这是使用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

有一件事我想要做,输出摘要而不是列表,但我不确定是否可以使用你的写作功能。有什么方法可以获得吗?

呼叫: 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