使用r将名为Natco的新列添加到合并的excel文件中

时间:2018-07-11 10:57:56

标签: r excel merge rbind

我正在尝试使用以下代码将多个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中做到这一点吗?

Ahsan

2 个答案:

答案 0 :(得分:0)

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

实施方式如下所示: df1 <- cbind(df1, "Natco"="df1") df2 <- cbind(df2, "Natco"="df2")

然后

df <- rbind(df1, ... , df2)

答案 1 :(得分:0)

这应该有效:

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])
}