自动分析多个.txt文件

时间:2012-04-12 18:53:58

标签: r large-data

我有两种类型(a + b)的txt文件的副本,即:

a1.txt a2.txt a3.txt... and b1.txt b2.txt b3.txt

我的目标是运行一个执行以下操作的r脚本:

read.table a1.txt
#run a bunch of code that chops and changes the data and then stores some vectors and data      frames.
w<-results
x<-results
detach a1.txt
read.table b1 .txt 
#run a bunch of code that chops and changes the data and then stores some vectors and data frames.
y<-results
z<-results
model1<-lm(w~y)
model2<-lm(x~z)

每次我想从中提取系数模型1的1个斜率和模型2的2个斜率。 我希望以自动方式在所有a和b文本文件对中运行此分析,并在另一个文件中以矢量格式构建系数。以后的分析。

到目前为止,我只能通过更简单的分析like this获得点数和价值。有没有人对如何在许多文件上运行这个更复杂的迭代有最好的想法?

编辑:到目前为止已尝试但尚未失败:

your<-function(x) 
{
files <- list.files(pattern=paste('.', x, '\\.txt', sep=''))
a <- read.table(files[1],header=FALSE)
attach(a)
w <- V1-V2
detach(a)
b <- read.table(files[2],header=FALSE)
z <- V1-V2
model <- lm(w~z)
detach(b)
return(model$coefficients[2])
}

slopes <- lapply(1:2, your)
Error in your(1) : object 'V1' not found

1 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

files <- list.files(pattern='.1\\.txt') # get a1.txt and b1.txt

如果您知道有多少文件(比方说10),您可以将上面的代码包装在一个函数中,并使用apply系列之一,具体取决于您所需的输出:

your.function(x) {
  files <- list.files(pattern=paste('.', x, '\\.txt', sep=''))
  a <- read.table(files[1])
  b <- read.table(files[2])

  w <- ...
  x <- ...

  y <- ...
  z <- ...

  model1 <- lm(w~y)
  model2 <- lm(x~z)

  return(c(model1$coefficients[2], moedl2$coefficients[2]))
}

slopes <- lapply(1:10, your.function)