0

I am reading my files into file_list. The data is read using read.csv, however, I want the data in datalist to have colnames as the file-names the file_list. The original files does not have a header. How do I change function(x) so that the the second column has colname similar to the file-name. The first column does not have to be unique.

file_list = list.files(pattern="*.csv")     

datalist = lapply(file_list, function(x){read.csv(file=x,header=F,sep = "\t")})
user2300940
  • 2,355
  • 1
  • 22
  • 35
  • 1
    When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Mar 29 '18 at 18:36

2 Answers2

2

How do I change function(x) so that the the second column has colname similar to the file-name?

datalist = lapply(file_list, function(x){
    dat = read.csv(file=x, header=F, sep = "\t")
    names(dat)[2] = x
    return(dat)
})

This will put the name of the file as the name of the second column. If you want to edit the name, use gsub or substr (or similar) on x to modify the string.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
1

You can just add another step.

names(datalist) <- file_list

Anonymous coward
  • 2,061
  • 1
  • 16
  • 29
  • 1
    This will switch the list names. I think OP is asking to rename the columns of the data frames in the list. – Gregor Thomas Mar 29 '18 at 18:43
  • You are correct. This would set you up to get the filenames if you split the list to a dataframe using `ldply`. Your solution is the correct one for what they wanted. – Anonymous coward Mar 29 '18 at 19:05