read.csv from list to get unique colnames

烂漫一生 提交于 2019-12-13 03:02:13

问题


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

回答1:


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.




回答2:


You can just add another step.

names(datalist) <- file_list



来源:https://stackoverflow.com/questions/49562784/read-csv-from-list-to-get-unique-colnames

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!