读取目录中的所有文件,并对每个数据框应用多种功能 [英] Read all files in directory and apply multiple functions to each data frame

查看:55
本文介绍了读取目录中的所有文件,并对每个数据框应用多种功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将R中的一组命令应用于目录中的所有单个.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的ape库):

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.

预先感谢, 丹妮.

推荐答案

您可以获取所有文件,然后使用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=TRUE, recursive=FALSE)
lapply(files, function(x) {
    t <- read.table(x, header=TRUE) # load file
    # apply function
    out <- function(t)
    # write to file
    write.table(out, "path/to/output", sep="\t", quote=FALSE, row.names=FALSE, col.names=TRUE)
})

这篇关于读取目录中的所有文件,并对每个数据框应用多种功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆