R语言读写excel文件

Python012

R语言读写excel文件,第1张

R语言读写excel表格

读文件常用的几种方法:

1.  library(readxl)

data <- read_excel("name.xlsx",sheet=1,col_names = T,col_types = NULL ,na="", skip=0)

2.   data <- read.table("name.txt",header = T,sep = "")

3.   read.csv(file.choose(),header = F,sep = ",")#逗号可删除

data <-data.frame(data$a,data$b)#合并成数据框结构

写入文件:

write.table(data,file = "data.csv",sep=",",row.names = F, col.names = F ,quote = F)

一、 安装RODBC库

1、进入R语言的GUI界面(RGUI.EXE),在菜单栏选择“程序包/安装程序包”(如图

2、在弹出的窗口里往下拉,选择RODBC如图,点击确定

3、在ODBC数据源管理器里将需要的数据库添加进去,这里笔者使用的是SQL Server2008,驱动程序选择Native Client10.0

3、在R语言窗口输入连接语句

>library(RODBC)

**这里是载入RODBC库

>channel<-odbcConnect("MyTest",uid="ripley",case="tolower")

**连接刚才添加进数据源的“MyTest”数据库

**ch <- odbcConnect("some dsn ", uid = "user ", pwd = "**** ")

**表示用户名为user,密码是****,如果没有设置,可以直接忽略

>data(USArrests)

**将“USArrests”表写进数据库里(这个表是R自带的)

>sqlSave(channel,USArrests,rownames = "state",addPK = TRUE)

**将数据流保存,这时候打开SQL Server就可以看到新建的USArrests表了

>rm(USArrests)

>sqlTables(channel)

**给出数据库中的表

>sqlFetch(channel,"USArrests",rownames = "state")

**输出USArrests表中的内容

>sqlQuery(channel,"select * from USArrests")

**调用SELECT查询语句并返回结果(如图)

>sqlDrop(channel,"USArrests")

**删除表

>odbcClose(channel)

**最后要记得关闭连接