【问题标题】:Automate analysis over multiple .txt files自动分析多个 .txt 文件
【发布时间】:2012-04-12 18:53:58
【问题描述】:

我有两种类型 (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

【问题讨论】:

  • 2 件事。首先,最好避免使用attachdetach。其次,(通过解决第一个问题可以避免!)在您阅读b 之后,您不会attach 它。而是使用 z &lt;- b$V1 - b$V2 之类的东西。
  • 在你回复我之前我刚刚破解了它。非常感谢!

标签: r large-data


【解决方案1】:

你可以这样做:

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)

【讨论】:

  • 嗨,贾斯汀,感谢您的回答,您能否澄清list.files(pattern=paste('.', x, '\\.txt', sep='')) 部分,我不确定('.', x, '\\.txt', sep='') 参数的含义
  • paste 接受任意数量的参数并将它们与指定的分隔符一起平滑(sep='' 不提供分隔符)。例如paste('foo', 'bar', sep=' ')paste('foo', 'bar', sep='!')。这有帮助吗?我只是将索引(数字 1 到 10)混合到匹配单个字符(a 或 b)加上 number.txt 的正则表达式中(因此如果 x=1,它应该找到 a1.txt 和 b1.txt)。我敢肯定,一清二楚!
猜你喜欢
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多