user3013423
user3013423

Reputation:

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

Upvotes: 0

Views: 1801

Answers (2)

Silence Dogood
Silence Dogood

Reputation: 3597

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);
  }
)

Upvotes: 0

Henk
Henk

Reputation: 3656

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)
}

Upvotes: 1

Related Questions