我是R的新学习者,我不知道如何从目录中读取数据。 我写的函数用于读取名称为“001.csv”,“002.csv”的csv文件...我不知道是否有任何快捷方式可以避免使用“if else”添加“00”或“0”。 此外,还有一个错误,因为我无法使用data [i](类型'closure'的对象不是子集)。那么如何保存我的数据?
reading <- function(directory, id = 1:500){
for(i in length(id)){
if(id[i]<10)
index <- paste("00",id[i], sep = "")
else if(id[i]<100)
index <- paste("0",id[i], sep = "")
else
index <- id[i]
data[i] <- read.csv(paste(directory,"/",index,".csv",sep = ""))
}
}
答案 0 :(得分:0)
我们可以使用sprintf
files <- sprintf('%03d.csv', 1:500)
files1 <- paste(directory, files, sep="/")
或单行
files1 <- sprintf('%s/%03d.csv', directory, 1:500)
lapply(files1, read.csv, sep="")
如果我们正在使用
reading <- function(directory, id = 1:500){
files1 <- sprintf('%s/%03d.csv', directory, id)
lapply(files1, read.csv, sep="")
}
或使用for
循环功能
reading <- function(directory, id = 1:500){
data <- vector('list', length(id))
for(i in seq_along(id)){
file <- sprintf('%s/%03d.csv', directory, id[i])
data[[i]] <- read.csv(file, sep="")
}
data
}
答案 1 :(得分:0)
或许更为多样化的方法:
folder_files <- list.files(path = "~/Documents/My Directory/",
pattern = "//d+.csv", ignore.case = T, full.names = T)
#you can freely adjust pattern to any regular expression which helps in the
#long term if you have a different pattern you want to catch
readin_df <- data.frame()
for (f in folder_files) {
df <- read.csv(f, sep = "")
readin_df <- rbind(df, readin_df)
}