R转换.csv文件格式到.txt或.xlsx) [read.csv and export data to
发布时间:2020-12-14 03:37:52 所属栏目:大数据 来源:网络整理
导读:现有多份 文件名相似 ( 比如文件名开头都以"Report"开头,"Report"之后跟进日期和时间 )并且 数据结构一致 的.csv格式文件,需要 用R把这些文件合并 ,并转化文件格式为.txt或者.xlsx。文件内容可参考如下范例: ID Name Age IQ 001 路飞 20 80 002 山治 22 1
现有多份文件名相似(比如文件名开头都以"Report"开头,"Report"之后跟进日期和时间)并且数据结构一致的.csv格式文件,需要用R把这些文件合并,并转化文件格式为.txt或者.xlsx。文件内容可参考如下范例:
需要考虑的因素有:
那么我可以写一个这样的函数:
# read all .csv files (file name beginning with same characters,same data structure) # combine them together and keep only the header of the first table # export as an entity of .txt file transcsv<-function(directory = "D:/RawData",startchar = "Report"){ # directory: the directory where you put the data source # startchar: the common fields/characteristics the file names start with setwd(directory) filename <- paste(startchar,"*.csv",sep="") filenames <- Sys.glob(filename) # can also try list.files() n <- 1 for (filename in filenames){ if (n == 1){ txtfile<-read.csv(filename,header = T,sep = ";") }else{ txtfile<-rbind(txtfile,read.csv(filename,sep = ";")) } n <- n + 1 } newname<-paste(startchar,"_All.txt",sep="") write.table(txtfile,newname,sep=";") } 上面涉及到的一些关键点有:
如果要将.csv转换成.xlsx格式(.xls格式的请自己去搜索package: WriteXLS,使用方法大同小异),需要在自定义函数里添加和修改一些地方:
==========================================================================================================
写这个函数的背景:
每周需要读取大量的.csv文件做报告,公司电脑是英文系统(不想在设置面板里改为中文),那么在用VBA读取.csv文件时,如果.csv里包含中文字符,读取到EXCEL之后会变成乱码,而将.csv变成.txt后再读取,就没有这种问题了(如果还是有问题,就要尝试一下在
write.table()
里添加一个arg:
fileEncoding = "UTF-8"
或者
= "ANSI"
)。
另,如果是英文系统,即使读取了.csv文件并用
write.xlsx()
写成.xlsx文件,也无法显示里面的中文,这里只是提供另一种思路。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |