如何在R语言中读入数据和导出存储数据

Python027

如何在R语言中读入数据和导出存储数据,第1张

1.R数据的保存与加载

可通过save()函数保存为.Rdata文件,通过load()函数将数据加载到R中。

[ruby] view plain copy

> a <- 1:10

> save(a,file='d://data//dumData.Rdata')

> rm(a)   #将对象a从R中删除

> load('d://data//dumData.Rdata')

> print(a)

[1]  1  2  3  4  5  6  7  8  9 10

2.CSV文件的导入与导出

下面创建df1的数据框,通过函数write.csv()保存为一个.csv文件,然后通过read.csv()将df1加载到数据框df2中。

[ruby] view plain copy

> var1 <- 1:5

> var2 <- (1:5)/10

> var3 <- c("R and","Data Mining","Examples","Case","Studies")

> df1 <- data.frame(var1,var2,var3)

> names(df1) <- c("VariableInt","VariableReal","VariableChar")

> write.csv(df1,"d://data//dummmyData.csv",row.names = FALSE)

> df2 <- read.csv("d://data//dummmyData.csv")

> print(df2)

VariableInt VariableReal VariableChar

1           1          0.1        R and

2           2          0.2  Data Mining

3           3          0.3     Examples

4           4          0.4         Case

5           5          0.5      Studies

3.通过ODBC导入与导出数据

RODBC提供了ODBC数据库的连接。

3.1从数据库中读取数据

odbcConnect()建立一个数据库连接,sqlQuery()向数据库发送一个SQL查询,odbcClose()关闭数据库连接。

[ruby] view plain copy

library(RODBC)

connection <- odbcConnect(dsn="servername",uid="userid",pwd="******")

query <- "SELECT * FROM lib.table WHERE ..."

# or read query from file

# query <- readChar("data/myQuery.sql", nchars=99999)

myData <- sqlQuery(connection, query, errors = TRUE)

odbcClose(connection)

sqlSave()和sqlUpdate()用于写入或更新一个ODBC数据库表。

3.2从Excel文件中导入与导出数据

[ruby] view plain copy

library("RODBC")

conn<-odbcConnectExcel("D:/data/Amtrak.xls")

Amtrak<-sqlFetch(conn,"Data")

close(conn)

1.对于简单文件,可以简单读取,ex1 <- read.table("ex1.txt")

2.对于复杂文件,ex1 <-read.table("文件名如ex1.txt",sep="\t",header=T,row.names = 1,comment.char="!",sep="\t")

read.table默认分隔符为\t

sep="\t"目的为识别行,对同一表格运行有无此命令的两种结果对比显而易见

header=T目的为把第一行设置为表头

比较复杂的文档需要跳过有些部分的,根据需要掉过部分的特点,如此下图文档不需要的部分都有感叹号, commeat.char="!"意思为跳过!那一行,去掉我们不需要的那部分, 即读出了表达矩阵

设置第一列为列名的参数是row.names = 1

read.CSV(("文件名",sep=",")#因为CSV默认分隔符是逗号

save(b,file="b_input.Rdata)#把读出来的文件b存为R语言专用数据文件,以后就可以直接load(file="b_input.Rdata)打开

library(readxl)#加载包,无法加载就安装

a<-read_excel("123.xlsx")#注意要把数据文件放在你打开的R-project目录下,不然读取不到

R语言学习笔记之聚类分析

使用k-means聚类所需的包:

factoextra

cluster #加载包

library(factoextra)

library(cluster)l

#数据准备

使用内置的R数据集USArrests

#load the dataset

data("USArrests")

#remove any missing value (i.e, NA values for not available)

#That might be present in the data

USArrests <- na.omit(USArrests)#view the first 6 rows of the data

head(USArrests, n=6)

在此数据集中,列是变量,行是观测值

在聚类之前我们可以先进行一些必要的数据检查即数据描述性统计,如平均值、标准差等

desc_stats <- data.frame( Min=apply(USArrests, 2, min),#minimum

Med=apply(USArrests, 2, median),#median

Mean=apply(USArrests, 2, mean),#mean

SD=apply(USArrests, 2, sd),#Standard deviation

Max=apply(USArrests, 2, max)#maximum

)

desc_stats <- round(desc_stats, 1)#保留小数点后一位head(desc_stats)

变量有很大的方差及均值时需进行标准化

df <- scale(USArrests)

#数据集群性评估

使用get_clust_tendency()计算Hopkins统计量

res <- get_clust_tendency(df, 40, graph = TRUE)

res$hopkins_stat

## [1] 0.3440875

#Visualize the dissimilarity matrix

res$plot

Hopkins统计量的值<0.5,表明数据是高度可聚合的。另外,从图中也可以看出数据可聚合。

#估计聚合簇数

由于k均值聚类需要指定要生成的聚类数量,因此我们将使用函数clusGap()来计算用于估计最优聚类数。函数fviz_gap_stat()用于可视化。

set.seed(123)

## Compute the gap statistic

gap_stat <- clusGap(df, FUN = kmeans, nstart = 25, K.max = 10, B = 500)

# Plot the result

fviz_gap_stat(gap_stat)

图中显示最佳为聚成四类(k=4)

#进行聚类

set.seed(123)

km.res <- kmeans(df, 4, nstart = 25)

head(km.res$cluster, 20)

# Visualize clusters using factoextra

fviz_cluster(km.res, USArrests)

#检查cluster silhouette图

Recall that the silhouette measures (SiSi) how similar an object ii is to the the other objects in its own cluster versus those in the neighbor cluster. SiSi values range from 1 to - 1:

A value of SiSi close to 1 indicates that the object is well clustered. In the other words, the object ii is similar to the other objects in its group.

A value of SiSi close to -1 indicates that the object is poorly clustered, and that assignment to some other cluster would probably improve the overall results.

sil <- silhouette(km.res$cluster, dist(df))

rownames(sil) <- rownames(USArrests)

head(sil[, 1:3])

#Visualize

fviz_silhouette(sil)

图中可以看出有负值,可以通过函数silhouette()确定是哪个观测值

neg_sil_index <- which(sil[, "sil_width"] <0)

sil[neg_sil_index, , drop = FALSE]

##          cluster    neighbor     sil_width

## Missouri    3          2        -0.07318144

#eclust():增强的聚类分析

与其他聚类分析包相比,eclust()有以下优点:

简化了聚类分析的工作流程

可以用于计算层次聚类和分区聚类

eclust()自动计算最佳聚类簇数。

自动提供Silhouette plot

可以结合ggplot2绘制优美的图形

#使用eclust()的K均值聚类

# Compute k-means

res.km <- eclust(df, "kmeans")

# Gap statistic plot

fviz_gap_stat(res.km$gap_stat)

# Silhouette plotfviz_silhouette(res.km)

##    cluster size ave.sil.width

## 1     1     13      0.31

## 2     2     29      0.38

## 3     3      8      0.39

#使用eclust()的层次聚类

# Enhanced hierarchical clustering

res.hc <- eclust(df, "hclust") # compute hclust

fviz_dend(res.hc, rect = TRUE) # dendrogam

#下面的R代码生成Silhouette plot和分层聚类散点图。

fviz_silhouette(res.hc) # silhouette plot

##   cluster size ave.sil.width

## 1    1     19      0.26

## 2    2     19      0.28

## 3    3     12      0.43

fviz_cluster(res.hc) # scatter plot

#Infos

This analysis has been performed using R software (R version 3.3.2)