简体   繁体   中英

loop for column names of a dataframe

This is quite a complicated question for me and I was hoping if anyone could help me with this.

I have around 500 csv files in my working directory. Each csv file has three columns of data. However only the second and third column has a column name while the first one does not have a column name. For example, one of my example csv file looks like this:

     name_1    name_2
23    34       65
43    34       23
54    12       21
65    12       23
76    14       23
76    45       12
87    76       54
78    21       65
78     23      45

What I want to do is:

1) read each csv file in R

2) give the column name ('col1') to the first column

3) Save the file back in the working directory.

I understand I need to show what I have done so far but thing is I haven't moved an inch with this and have absolutely no idea how to go about it? I will be really grateful if anyone could help me with this.

Thanks a lot

filenames = list.files(pattern='[.]csv')

for(i in 1:length(filenames)){
  f <- read.csv(filenames[i],header=TRUE)
  colnames(f)[1] = "col1"
  write.csv(f, file = filenames[i], row.names=FALSE)
}

See if this works:

set working directory:

dir='/yourpath/'
setwd(dir)

Use list.files to get list of all files with extension '.csv', read data, rename column and overwrite csv

process all files

lapply(list.files(pattern = "[.csv]$"), 
  function(x) {
    cat('Processing file:', x, '\n');
    df <- read.csv(x, stringsAsFactors = FALSE, header = TRUE);
    colnames(df)[1] <- 'col1';
    write.csv(df, x);
  }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM