0

I currently use the following code to transform and tidy my .csv to my required format.

mydf<-read.csv("mydf.csv",header=F)
mydf<-mydf[-c(1,2,3,4,5,6,7,8,9,10,11)]
colnames(mydf)[colnames(mydf)=="V12"]<-"ts"
colnames(mydf)[colnames(mydf)=="V13"]<-"cs"
colnames(mydf)[colnames(mydf)=="V14"]<-"lat"
colnames(mydf)[colnames(mydf)=="V15"]<-"long"
colnames(mydf)[colnames(mydf)=="V16"]<-"v"
colnames(mydf)[colnames(mydf)=="V17"]<-"a"
colnames(mydf)[colnames(mydf)=="V18"]<-"hr"
colnames(mydf)[colnames(mydf)=="V19"]<-"pl"
colnames(mydf)[colnames(mydf)=="V20"]<-"mp"
colnames(mydf)[colnames(mydf)=="V21"]<-"sl"
colnames(mydf)[colnames(mydf)=="V22"]<-"o"
write.csv(mydf,"mydf.csv",row.names = F)

This is quite simple for an individual .csv as I just change the file name but I am now wishing to perform this on 1000's of file with the same directory and I'd rather find a better way than manually changing to file name 1000 times. All the .csv's are in the exact same format.

I've searched this forum as well as other's across the internet but I can't seem to find or execute an appropriate solution.

Any help would be appreciated.

Cheers,

JPC

JPC
  • 25
  • 3
  • 1
    Just use `files <- list.files(pattern = "\\.csv"); lapply(files, read.csv)` and change the column names in the `lisst` – akrun Jul 23 '19 at 03:14

1 Answers1

0

I didn't test this yet, but I think it should work.

library(data.table)
csv_list <- list.files(path = dir_name, pattern="*.csv")

lapply(csv_list, function(x) {
             df <- read.csv(x, header = FALSE);
              setnames(df, old = c('V12','V13'), new = c('ts','cs'));
              write.csv(df, x, row.names = FALSE)
             }
)

Instead of setnames from data.table; the dplyr options rename is availanle too. See Rename multiple columns by names for examples.

kangaroo_cliff
  • 6,067
  • 3
  • 29
  • 42