【问题标题】:How to read and combine multiple .txt files in R with multiple rows and columns into a single data frame? Data from Li-840如何读取 R 中的多个 .txt 文件并将其与多个行和列组合到一个数据框中?来自 Li-840 的数据
【发布时间】:2021-06-22 15:52:43
【问题描述】:

我正在尝试使用 R 来读取和合并多个 .txt 文件。我还想根据文件名添加列。 .txt 文件是使用 licor li-840 收集的气体交换数据。每个 .txt 文件都是单个样本的时间序列。命名方案是 year.month.day.Time.Shrub.Treatment.Sample(例如 2021.6.9.T0.20.w3.15)。 .txt 文件以日期和开始时间的行开头。第 2 行有 8 个列名。

为清晰起见进行编辑 目标:

  • 如何读取多个 .txt 文件
  • 如何分隔文件名并添加为列
  • 如何将 .txt 文件合并到单个数据帧中

在 cmets 中,我尝试了以下代码:

files <- map(.x = cfiles, ~read.delim(.x,skip=1, header=TRUE))
%>% bind_rows()
%>% map2(.y= cfiles, ~mutate(.x, campaign = .y))

输出错误是:

Error in UseMethod("mutate") :
no applicable method for 'mutate' applied to an object of class "character"

.txt 文件的一个示例是: 文件名:2021.6.9.T0.20.w3.15

sample data image

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以使用 purrrdplyr::bind_rows 轻松完成此操作

    names 将是您的文件列表。

    files <- map(.x = names, ~read.delim(.x)) %>%
              bind_rows()%>%
              map2(.y= names, ~mutate(.x, campaign = .y))
    

    我以前也有过这种数据结构。

    purrr:map() 迭代一个列表,purrr:map2() 迭代两个列表。

    【讨论】:

    • 我对 R 非常陌生,这是我第一次使用 txt 文件。到目前为止,我只有在文件中读取的代码:conductance_data
    • 我重新审视了这个问题,并能够创建文件列表。我修改了您的代码以删除 .txt 文件的第一行并将第二行用作标题。文件 % bind_rows()%>% map2(.y= cfiles, ~mutate(.x, 活动= .y)) 当我运行该行时,它返回此错误: UseMethod("mutate") 中的错误:没有适用于“mutate”的方法应用于“character”类的对象
    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 2016-03-21
    • 2021-08-18
    • 2019-12-22
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多