Issue
I read multiple csv files and get a list of 11 data frames. Now I want to use each data frame in the list to get a new table and save it to a csv file with the origin name separately.
I read csv file by
path <- "D:/DATA/01/processdata/singlecity"
fileNames = list.files(path, pattern="*.csv$")
filePath <- sapply(fileNames, function(x){
paste(path,x,sep='/')})
dfs <- lapply(filePath, function(x){
read.csv(x, header=T)})
then get a list of dataframe like :
EU CHINA USA
for (i in data){
y <- data.table(i)
y <- dplyr::filter(y, grepl('2002|2003|2004|2005|2006', V2))
write.csv(y, "y.csv')
}
what I want to output is that:
EU_t1.csv
CHINA_t2.csv
USA_t3.csv
I don't know how to use write.csv to return different files based on origin data frame name.
Solution
You can try the following :
path <- "D:/DATA/01/processdata/singlecity"
fileNames = list.files(path, pattern="*.csv$", full.names = TRUE)
lapply(seq_along(fileNames), function(x){
file <- fileNames[x]
data <- subset(read.csv(file), grepl('2002|2003|2004|2005|2006', V2))
write.csv(data, sprintf('D:/DATA/01/processdata/singlecity/T1/%s_t%d.csv',
tools::file_path_sans_ext(basename(file)), x), row.names = FALSE)
})
Answered By - Ronak Shah Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.