循环遍历R中目录中的所有文件,应用多个命令 [英] Looping through all files in directory in R, applying multiple commands
问题描述
我需要在一个目录中的所有单个 .txt
文件(大约300)中应用一组命令。
I need to apply a set of commands in R to all the individual .txt
files (around 300) in a directory.
我不太熟悉R,所以在线查看关于循环的所有帮助都是令人困惑的,或者我不能解决如何应用一个循环,当你需要应用多个命令每个文件
I'm not very familiar with R, so all the help I've looked at online about looping is confusing, or I can't work out how to apply a loop when you need to apply multiple commands to each file.
我需要应用到目录中的每个文件(系统发育树)的命令(使用R的猿库):
The commands I need to apply to each file (phylogenetic trees) within the directory are (which uses R's ape library):
testtree <- read.tree("tree123.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="unrootedtree123.txt")
如何应用一个将这些命令应用于每个单独的.txt文件(使用R或Unix命令行)?输出(例如unrootedtree123.txt)将需要为每个单独的文件使用不同的名称。
How do I apply a loop which will apply these commands to each individual .txt file (either using R or in the Unix command line)? The output (e.g. unrootedtree123.txt) will need to have a different name for each individual file.
提前感谢
Dani。
Thanks in advance, Dani.
推荐答案
您可以获取所有文件,然后循环使用 lapply
并应用您想要的任何功能应用如下:
You can get all the files and then loop using lapply
and apply whatever function you want to apply as follows:
files <- list.files(path="path/to/dir", pattern="*.txt", full.names=T, recursive=FALSE)
lapply(files, function(x) {
t <- read.table(x, header=T) # load file
# apply function
out <- function(t)
# write to file
write.table(out, "path/to/output", sep="\t", quote=F, row.names=F, col.names=T)
})
这篇关于循环遍历R中目录中的所有文件,应用多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!