我知道如何单独做到这一点。但是,我有超过1000个文件。我决定使用for循环。但是,似乎我没有找到正确的方法来评估我的变量。
这是我的代码
setwd('C:/data')
filenames=dir() #find file names
for (i in filenames){
adt = substr(x = i, start = 1, stop = nchar(i)-4)
name=paste("data_", adt, sep="")
assign(name, read.csv(i,header=T,sep=",")) #read each file and assign a variable name starting with data_ to it
func=paste('name[is.na(name)] <- 0',sep="") # here is the place I have problem. R will not consider name is a parameter whose values change in each iteration
eval((text=func))
}
答案 0 :(得分:1)
您可以将read.csv
的结果分配给临时变量,替换NA
,然后分配给name
for (i in filenames){
adt = substr(x = i, start = 1, stop = nchar(i)-4)
name=paste("data_", adt, sep="")
tmp <- read.csv(i, header=TRUE, sep=",")
tmp[is.na(tmp)] <- 0
assign(name, tmp, pos=.GlobalEnv)
}
答案 1 :(得分:1)
library(plyr)
# change the pattern to match whatever file type you are reading
filenames <- list.files(path = ".", pattern = ".csv", all.files = FALSE,
full.names = FALSE, recursive = FALSE, ignore.case = FALSE)
data <- llply(filenames, read.csv)
cleaned_data <- llply(data, function(x) {x[is.na(x)] <- 0; return(x)})
names(cleaned_data) <- paste0("data_", 1:length(cleaned_data))