我有多个csv文件要导入到R中。
如何将多个文件读入R中,并从第一列中的文件名中添加带有日期文本的列?
在此需要:
对于每个csv文件,取文件名中的日期,并在重新绑定它们之前将其添加为每个dataframe的第一列。
下面是在文件名中没有日期列的代码:
all <- lapply(c("file_10-16-2017.csv",
"file_10-17-2017.csv",
"file_10-18-2017.csv",
function(x){
read_csv(x, skip = 10)}) %>% bind_rows()
我希望我的最终结果是这样的:
Date_Pulled Week Date spot1 Site ID test
10-16-2017 10/15/17 10/16/2017 trial trial134
. . . . .
. . . . .
. . . . .
10-17-2017 10/15/17 10/16/2017 trial trial134
. . . . .
. . . . .
. . . . .
任何帮助都会很好,谢谢!
发布于 2017-12-01 05:25:57
我想出了另一个方法:
filenames <- list.files(path = ".", pattern = NULL, all.files = FALSE, full.names = FALSE, recursive = FALSE, ignore.case = FALSE)
read_csv_filename <- function(filenames){
ret <- read.csv(filenames, skip = 10)
ret$Source <- filenames #EDIT
ret
}
import.list <- ldply(filenames, read_csv_filename)
这应该能起作用
发布于 2017-12-01 04:20:17
首先,将您想要读取的所有文件放在一个单独的工作目录中,并将工作目录更改为这个目录。
# 1. change wd
setwd('new_file_path')
# 2. get files from that directory
my_files <- list.files()
# 3. read in all files, skipping first 10 lines
library(readr)
dat_list <- lapply(my_files, read_csv, skip = 10)
# 4. mutate a new column, which is the name of the file
library(dplyr)
dat_list_new <- lapply(dat_list, function(x) {
mutate(x,
new_col_one = names(x))
})
# 5. port this list of data frames to the global environment
names(dat_list_new) <- my_files # set the names of the dataframes
list2env(dat_list_new,envir=.GlobalEnv)
https://stackoverflow.com/questions/47586435
复制相似问题