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

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

问题描述

我需要将 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="	", quote=FALSE, row.names=FALSE, col.names=TRUE)
})

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

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