Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

csv - How to automate subsetting multiple files using r

Hi guys am new to R and I am comfortable with creating subsets if i handle one file at a time .... But I am having trouble automating that to multiple files...So in my case,I want to automate the process of subsetting multiple csv files which are present in multiple subfolders of a given folder ...I want to create multiple subset files which include say the the 100 rows of each file and write them into new files and the name of the subsetted files should be same as that of the file from which they were subsetted... Any help appreciated... Thanks!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I created a couple of subfolders in my folder Temp. If the working directory is Temp. Assuming that the number of rows in each dataset is >= 100

files <- list.files(recursive=TRUE, full.names=TRUE)
files
#[1] "./Temp1/file1.csv"   "./Temp2/file2_2.csv" "./Temp2/file2.csv" 

lst1 <- lapply(files, function(x) read.csv(x, sep='')[1:100,])
Pref <- sub("/[^/]+$", '', files)

The subset files are then written to the corresponding folders along with the old file.

invisible(lapply(seq_along(lst1), function(i) 
            write.csv(lst1[[i]],paste(Pref[i],paste0('Subset',
           basename(files[i])), sep="/"), quote=FALSE, row.names=FALSE)))

list.files(recursive=TRUE, full.names=TRUE)
#[1] "./Temp1/file1.csv"         "./Temp1/Subsetfile1.csv"  
#[3] "./Temp2/file2_2.csv"       "./Temp2/file2.csv"        
#[5] "./Temp2/Subsetfile2_2.csv" "./Temp2/Subsetfile2.csv"  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...