循环遍历R中的文件

时间:2012-07-02 08:01:01

标签: r loops statistics

我使用R来计算文件中列的平均值,如下所示:

R
file1 = read.table("x01")
mean(file1$V4)

但是我没有经验构建涉及R的循环,只有bash。 我如何将其转换为为文件夹中的每个文件执行此操作的循环,并将输出保存到一个文件名和平均值为每行2列的文件中? 例如:

x01(or file1 if that is simpler) 23.4
x02 25.4
x03 10.4

(不介意解决方案是bash和R还是R) 非常感谢你的帮助!

使用bash和R的其中一个解决方案的当前错误:

Error in `[.data.frame`(read.table("PercentWindowConservedRanked_Lowest_cleanfor1000genomes_1000regions_x013",  : 
  undefined columns selected
Calls: mean -> [ -> [.data.frame
Execution halted

3 个答案:

答案 0 :(得分:4)

这类似于@jmsigner所做的,但稍作修改。例如,最后写入文件。该代码尚未经过测试。

out <- lapply(list.files(), FUN = function(x) {
    m <- mean(read.table(x, header = TRUE)$V4)
    return(m)
  })
result <- do.call("cbind", out) #merge a list column-wise
# before writing, you can make column names pretty with colnames()
# e.g. colnames(result) <- c("x01", "x02")
write.table(result, file = "means.txt")

答案 1 :(得分:3)

假设列的名称始终相同,您可以在R:

中执行以下操作
out.file <- 'means.txt'
for (i in list.files()) {
    tmp.file <- read.table(i, header=TRUE)  # Not sure if you have headers or not
    tmp.mean <- mean(tmp.file1$V4)
    write(paste0(i, "," tmp.mean), out.file, append=TRUE)
}

或者更多bash:

for i in $(ls *)
do
  mean=$(Rscript -e "mean(read.table('$i', header=T)[, 'V4'])")
  echo $i,$mean >> means.txt
done

答案 2 :(得分:2)

我的解决方案也类似于@jmsinger,但您可以在代码本身中指定文件的路径,然后像这样计算平均值:

filename <- system("ls /dir/",intern=TRUE)

for(i in 1:length(filename)){

file <- read.table(filename[i],header=TRUE) ## if you have headers in your files ##
mean <- mean(file$V4)

write.table(mean,file=paste("/dir",paste("mean",filename[i],sep="."),sep="/")) 
##if you wish to write the means of all the files in seperate files rather than one.
}

希望这会有所帮助

相关问题