【问题标题】:add a new column named Natco to the merged excel file using r使用 r 将名为 Natco 的新列添加到合并的 excel 文件中
【发布时间】:2018-07-11 10:57:55
【问题描述】:

我正在尝试使用以下代码将多个 excel 文件合并为一个:

df <- rbind(df1, df2, df3, df4, df5)

这段代码运行正确,并给了我正确的输出。但是我需要在合并数据框的末尾添加新列(Natco),这可以添加每个数据框的名称,该文件来自该文件的来源;

col1      col2   col3    col4    col5    Natco
5200      2018   text    short   term    df1
5300      2014   text    short   term    df2
5400      2017   string  short   term    df3
...       ...     ...     ...     ...    ...

有人知道如何在 R 中做到这一点吗?

阿山

【问题讨论】:

  • 您使用哪个包将 excel 文件导入 R?
  • 您应该在merging 之前添加一列Natco,其中包含数据框的名称。这样,最终结果将包含一列,其中包含正确的 Natco 信息。
  • @Mislav,我',使用readxl包加载excel文件

标签: r excel merge rbind


【解决方案1】:

您可以将“Natco”列绑定到每个 df priot 到 rbind。

实现类似于: df1 <- cbind(df1, "Natco"="df1") df2 <- cbind(df2, "Natco"="df2")

然后

df &lt;- rbind(df1, ... , df2)

【讨论】:

    【解决方案2】:

    这应该可行:

    library(readxl)
    
    excel_files <- list.files("fullPathToFolderWhereExcelFilesSits", full.names = TRUE)
    df <- lapply(excel_files, read_xlsx, sheet = 1L)
    for(i in 1:length(excel_files)){
      df[[i]]["Natco"] <- gsub(".*/", "", excel_files[i])
    }
    

    【讨论】:

    • 对我不起作用。此代码向我抛出错误“*tmp*[[i]] 中的错误:下标越界”。这是什么类型的问题?
    • 我试过了,它对我有用。在哪一行之后出现错误?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    相关资源
    最近更新 更多