【问题标题】:How to open a series of files with the same path and plot them如何打开一系列具有相同路径的文件并绘制它们
【发布时间】:2018-04-16 16:46:03
【问题描述】:

我想在 R 中绘制一系列 txt 文件,但是当我有几十个文件时,我需要帮助构建一个 for 循环来自动执行此操作。

我当前的脚本,对于一些文件来说很好,只是这个两行重复代码:

data <- read.table("/path/filename1.txt")
    plot(data, type = 'l', ylim=c(0,100), xlim = c(350,900))

data2 <- read.table("/path/filename2.txt")
    points(data, type = 'l', ylim=c(0,100), xlim = c(350,900))

data3 <- read.table("/path/filename3.txt")
    points(data, type = 'l', ylim=c(0,100), xlim = c(350,900))

data3 <- read.table("/path/filename3.txt")
    points(data, type = 'l', ylim=c(0,100), xlim = c(350,900))

我确信有一种更简单的方法可以使用 for 循环执行此操作,但我不熟悉 R 并且不知道如何完成此操作。

感谢您的帮助!

【问题讨论】:

标签: r for-loop plot


【解决方案1】:

由于我没有你的文件,这段代码没有经过测试,但它可以工作。

首先设置你的工作目录,然后应用以下......

读取所有文件

Files <- lapply(list.files(pattern = "\\.txt$"), read.table)

绘制它们..

lapply(Files, function(x) points(x, type = 'l', ylim=c(0,100), xlim = c(350,900)))

【讨论】:

  • 我认为应该先调用plot(Files[[1]]),然后再调用lapply(Files[[-1]], function(x) points(x))。
  • 要在基础 R 中静默绘图并具有 lapply 风格的紧凑语法,我们可以使用 Vectorize
【解决方案2】:

您可以按照您的建议使用 for 循环来执行此操作,如下所示:

files <- c('/path/filename1.txt', '/path/filename2.txt')

for(file in files)
{
  data <- read.table(file)
  plot(data, type = 'l', ylim=c(0,100), xlim = c(350,900))
}

在这种情况下,您将文件路径存储在名为 files 的向量中,然后对 files 的每个单独成员执行相同的操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-24
    • 2011-04-28
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多