[R] Importing, renaming columns and exporting mulitple csv files in R

arun smartpink111 at yahoo.com
Thu Sep 26 06:52:16 CEST 2013



Hi,
Try:
If the files are all in the same working directory, 
#for example
list.files() # 3 files in my WD
#[1] "file1.csv" "file2.csv" "file3.csv"


 lapply(list.files(),function(x) {names1<-read.csv(x,header=TRUE); names(names1)[c(19,23)]<- c("Redundant","Reef % cover"); dat1<- subset(names1,select=-c(31:38)); names(dat1)[c(1,11,22,31)]<- c("","Confidence","","Comments"); names(dat1);write.csv(dat1,paste0("Modified_",x),row.names=FALSE,na="") })

A.K.



----- Original Message -----
From: Jacquomo Monk <jacquomo.monk at deakin.edu.au>
To: r-help at r-project.org
Cc: 
Sent: Wednesday, September 25, 2013 9:13 PM
Subject: [R] Importing,	renaming columns and exporting mulitple csv files in R

Hi All,

I have 1029 *.csv files that I would like read individually into R, delete
some columns and rename others, and then export individually using the
original file names. 

I have written some script to do this for an individual file (script below),
but cannot get it to loop through all the files in the directory. 

> name1<-read.table(file="FID-AW1775_DV0228012H_
> 20080518.csv",sep=",",header=TRUE)

> names(name1)[23]<-"Reef % cover" ######### renames column 23
> names(name1)[19]<-"Redundant" ######### renames column 19

> data <- subset(name1, select=-c(31:38)) ######### deletes column 31-38
> names(data)[31]<-"Comments" ######### renames column 31
> names(data)[11]<-"Confidence" ######### renames column 11
> names(data)[1]<-"" ######### renames column 1
> names(data)[22]<-"" ######### renames column 22
  
> names(data) ##### check correct columns have been deleted and renamed
  
> write.csv(data,file = "FID-AW1775_DV0228012H_
> 20080518_v2.csv",sep=",",col.names=TRUE,row.names=FALSE, na="")


I have tried looping using > For (i in 1:length(files)){... but it seams to
read all the files into one massive file rather than process them
individually. 

Any ideas on how to get this to loop on individual files and write them out
again would be appreciated.

Chrs,

Jac



--
View this message in context: http://r.789695.n4.nabble.com/Importing-renaming-columns-and-exporting-mulitple-csv-files-in-R-tp4676951.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list