[R] condense repetitive code for read.csv and rename.vars

arun smartpink111 at yahoo.com
Thu Aug 15 05:01:26 CEST 2013


HI,
You could try:
#If all the files are in the working directory:

vec1<-list.files() #Created 3 dummy files in my WD

vec1
#[1] "mergedStatstA.csv" "mergedStatstB.csv" "mergedStatstC.csv"
library(gdata)

lapply(seq_along(vec1),function(i) {x1<-read.csv(vec1[i],header=TRUE,sep="\t");x2<-rename.vars(x1,from="X",to="Statistics.Calculated",info=FALSE);write.csv(x2,paste0("Modified_",vec1[i]),row.names=FALSE)}) ###If you want #to save it as a different file name.
list.files()
#[1] "mergedStatstA.csv"          "mergedStatstB.csv"         
#[3] "mergedStatstC.csv"          "Modified_mergedStatstA.csv"
#[5] "Modified_mergedStatstB.csv" "Modified_mergedStatstC.csv"
vec2<- list.files()[grep("Modified",list.files())]

sapply(seq_along(vec2),function(i){x1<-read.csv(vec2[i],header=TRUE); colnames(x1)})
#     [,1]                    [,2]                    [,3]                   
#[1,] "Statistics.Calculated" "Statistics.Calculated" "Statistics.Calculated"
#[2,] "col2"                  "col3"                  "col4"  

A.K.



----- Original Message -----
From: bcrombie <bcrombie at utk.edu>
To: r-help at r-project.org
Cc: 
Sent: Wednesday, August 14, 2013 3:43 PM
Subject: [R] condense repetitive code for read.csv and rename.vars

Is there a more concise way to write the following code?

library(gdata)
mydataOUTPUTrtfA <- read.csv("mergedStatstA.csv")
save(mydataOUTPUTrtfA, file="mydataOUTPUTrtfA.RData")
mydataOUTPUTrtfA <- rename.vars(mydataOUTPUTrtfA, from="X",
to="Statistics.Calculated", info=FALSE)

mydataOUTPUTrtfB <- read.csv("mergedStatstB.csv")
save(mydataOUTPUTrtfB, file="mydataOUTPUTrtfB.RData")
mydataOUTPUTrtfB <- rename.vars(mydataOUTPUTrtfB, from="X",
to="Statistics.Calculated", info=FALSE)

mydataOUTPUTrtfC <- read.csv("mergedStatstC.csv")
save(mydataOUTPUTrtfC, file="mydataOUTPUTrtfC.RData")
mydataOUTPUTrtfC <- rename.vars(mydataOUTPUTrtfC, from="X",
to="Statistics.Calculated", info=FALSE)

I will have a series of mydataOUTPUTrtf files spanning a large portion of
the alphabet, so to speak:
e.g. mydataOUTPUTrtfA to mydataOUTPUTrtfG  --- thanks for your help



--
View this message in context: http://r.789695.n4.nabble.com/condense-repetitive-code-for-read-csv-and-rename-vars-tp4673783.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