set.seed(1)
x<-rnorm(1000)
hist(x, freq=T, breaks = 10)
lines(density(x), lwd=2, col="blue")
t <- seq(-3, 3, by=0.01)
lines(t, 550*dnorm(t,0,1), col="magenta") # add the theoretical density line

hist(x, freq=F, breaks = 10)
lines(density(x), lwd=2, col="blue")

plot(density(x))

library(rvest)
## Loading required package: xml2
wiki_url <- read_html("http://wiki.socr.umich.edu/index.php/SOCR_LetterFrequencyData")
html_nodes(wiki_url, "#content")
## {xml_nodeset (1)}
## [1] <div id="content" class="mw-body-primary" role="main">\n\t<a id="top ...
## {xml_nodeset (1)}
## [1] <div id="content" class="mw-body-primary" role="main">\n\t<a id="top...
letter<- html_table(html_nodes(wiki_url, "table")[[1]])
summary(letter)
##     Letter             English            French            German       
##  Length:27          Min.   :0.00000   Min.   :0.00000   Min.   :0.00000  
##  Class :character   1st Qu.:0.01000   1st Qu.:0.01000   1st Qu.:0.01000  
##  Mode  :character   Median :0.02000   Median :0.03000   Median :0.03000  
##                     Mean   :0.03667   Mean   :0.03704   Mean   :0.03741  
##                     3rd Qu.:0.06000   3rd Qu.:0.06500   3rd Qu.:0.05500  
##                     Max.   :0.13000   Max.   :0.15000   Max.   :0.17000  
##     Spanish          Portuguese        Esperanto          Italian       
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.00000   Min.   :0.00000  
##  1st Qu.:0.01000   1st Qu.:0.00500   1st Qu.:0.01000   1st Qu.:0.00500  
##  Median :0.03000   Median :0.03000   Median :0.03000   Median :0.03000  
##  Mean   :0.03815   Mean   :0.03778   Mean   :0.03704   Mean   :0.03815  
##  3rd Qu.:0.06000   3rd Qu.:0.05000   3rd Qu.:0.06000   3rd Qu.:0.06000  
##  Max.   :0.14000   Max.   :0.15000   Max.   :0.12000   Max.   :0.12000  
##     Turkish           Swedish            Polish          Toki_Pona      
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.00000   Min.   :0.00000  
##  1st Qu.:0.01000   1st Qu.:0.01000   1st Qu.:0.01500   1st Qu.:0.00000  
##  Median :0.03000   Median :0.03000   Median :0.03000   Median :0.03000  
##  Mean   :0.03667   Mean   :0.03704   Mean   :0.03704   Mean   :0.03704  
##  3rd Qu.:0.05500   3rd Qu.:0.05500   3rd Qu.:0.04500   3rd Qu.:0.05000  
##  Max.   :0.12000   Max.   :0.10000   Max.   :0.20000   Max.   :0.17000  
##      Dutch            Avgerage      
##  Min.   :0.00000   Min.   :0.00000  
##  1st Qu.:0.01000   1st Qu.:0.01000  
##  Median :0.02000   Median :0.03000  
##  Mean   :0.03704   Mean   :0.03741  
##  3rd Qu.:0.06000   3rd Qu.:0.06000  
##  Max.   :0.19000   Max.   :0.12000
par(mfrow=c(1, 2))
pie(letter$English[1:10], labels=letter$Letter[1:10], col=rainbow(10, start=
0.1, end=0.8), clockwise=TRUE, main="First 10 Letters Pie Chart")
pie(letter$English[1:10], labels=letter$Letter[1:10], col=rainbow(10, start=
0.1, end=0.8), clockwise=TRUE, main="First 10 Letters Pie Chart")
legend("topleft", legend=letter$Letter[1:10], cex=1.3, bty="n", pch=15, pt.cex=1.8, col=rainbow(10, start=0.1, end=0.8), ncol=1)

Heat Maps

A neuroimaging genetics casestudy data about the association (p-values) of different brain regions of interest (ROIs) and genetic traits (SNPs) for Alzheimer’s disease (AD) patients, subjects with mild cognitive impairment (MCI), and normal controls (NC).The data are 2D arrays where the rows represent different genetic SNPs, columns represent brain ROIs, and the cell values represent the strength of the SNP-ROI association, a probability value (smaller p-values indicate stronger neuroimaging-genetic associations).

AD_Data <- read.table("https://umich.instructure.com/files/330387/download?download_frd=1", header=TRUE, row.names=1, sep=",", dec=".")
MCI_Data <- read.table("https://umich.instructure.com/files/330390/download?download_frd=1", header=TRUE, row.names=1, sep=",", dec=".")
NC_Data <- read.table("https://umich.instructure.com/files/330391/download?download_frd=1", header=TRUE, row.names=1, sep=",", dec=".")

require(graphics)
require(grDevices)
library(gplots)
## 
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
## 
##     lowess
AD_mat <- as.matrix(AD_Data); class(AD_mat) <- "numeric"
MCI_mat <- as.matrix(MCI_Data); class(MCI_mat) <- "numeric"
NC_mat <- as.matrix(NC_Data); class(NC_mat) <- "numeric"

rcAD <- rainbow(nrow(AD_mat), start = 0, end = 1.0); ccAD<-rainbow(ncol(AD_mat), start = 0, end = 1.0)
rcMCI <- rainbow(nrow(MCI_mat), start = 0, end=1.0); ccMCI<-rainbow(ncol(MCI_mat), start=0, end=1.0)
rcNC <- rainbow(nrow(NC_mat), start = 0, end = 1.0); ccNC<-rainbow(ncol(NC_mat), start = 0, end = 1.0)

hvAD <- heatmap(AD_mat, col=cm.colors(256), scale="column", RowSideColors = rcAD, ColSideColors = ccAD, margins = c(2, 2), main="AD Cohort")

hvMCI <- heatmap(MCI_mat, col = cm.colors(256), scale = "column", RowSideColors = rcMCI, ColSideColors = ccMCI, margins = c(2, 2), main="MCI Cohort")

hvNC <- heatmap(NC_mat, col=cm.colors(256), scale="column", RowSideColors = rcNC, ColSideColors = ccNC, margins = c(2, 2), main="NC Cohort")

x<-runif(50)
y<-runif(50)
plot(x, y, main="Scatter Plot")

library(ggplot2)
## Registered S3 methods overwritten by 'ggplot2':
##   method         from 
##   [.quosures     rlang
##   c.quosures     rlang
##   print.quosures rlang

cat <- rep(c("A", "B", "C", "D", "E"), 10)
plot.1 <- qplot(x, y, geom="point", size=5*x, color=cat, main="GGplot with Relative Dot Size and Color")
print(plot.1)

z<-runif(50)
pairs(data.frame(x, y, z))

data1 <- read.table('https://umich.instructure.com/files/399128/download?download_frd=1', header=T)
head(data1)
##          STFIPS majorfundtype FacilityType Ownership Focus PostTraum GLBT
## 1     southeast             1            5         2     1         0    0
## 2     southeast             3            5         3     1         0    0
## 3     southeast             1            6         2     1         1    1
## 4    greatlakes            NA            2         2     1         0    0
## 5 rockymountain             1            5         2     3         0    0
## 6       mideast            NA            2         2     1         0    0
##   num qual supp
## 1   5   NA   NA
## 2   4   15    4
## 3   9   15   NA
## 4   7   14    6
## 5   9   18   NA
## 6   8   14   NA
attach(data1)

plot(data1[, 9], data1[, 10], pch=20, col="red", main="qual vs supp")

pairs(data1[, 5:10])

plot.2 <- qplot(qual, supp, data = data1, geom = c("point", "smooth"))
print(plot.2)
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
## Warning: Removed 2862 rows containing non-finite values (stat_smooth).
## Warning: Removed 2862 rows containing missing values (geom_point).

library("xml2"); library("rvest")
wiki_url <- read_html("http://wiki.socr.umich.edu/index.php/SOCR_Data_Dinov_021708_Earthquakes")
html_nodes(wiki_url, "#content")
## {xml_nodeset (1)}
## [1] <div id="content" class="mw-body-primary" role="main">\n\t<a id="top ...
## {xml_nodeset (1)}
## [1] <div id="content" class="mw-body-primary" role="main">\n\t<a id="top...
earthquake <- html_table(html_nodes(wiki_url, "table")[[2]])
plot6.1<-ggplot(earthquake, aes(Depth, Latitude, group=Magt, color=Magt))+geom_point()
plot6.2<-ggplot(earthquake, aes(Depth, Latitude, group=Magt, color=Magt))+geom_point(position = position_jitter(w = 0.3, h = 0.3), alpha=0.5)
print(plot6.1)

print(plot6.2)

ggplot(earthquake, aes(Depth, Latitude, group=Magt, color=Magt,label=rownames(earthquake)))+
geom_point(position = position_jitter(w = 0.3, h = 0.3), alpha=0.5)+
geom_text()

ggplot(earthquake, aes(Depth, Latitude, group=Magt, color=Magt, label=rownames(earthquake)))+
geom_point(position = position_jitter(w = 0.3, h = 0.3), alpha=0.5)+
geom_text(check_overlap = T,vjust = 0, nudge_y = 0.5, size = 2,angle = 45)

# Or you can simply use the text to denote the positions of points.
ggplot(earthquake, aes(Depth, Latitude, group=Magt, color=Magt,
label=rownames(earthquake)))+
geom_text(check_overlap = T,vjust = 0, nudge_y = 0, size = 3,angle = 45)

x <- matrix(runif(50), ncol=5, dimnames=list(letters[1:10], LETTERS[1:5]))
x
##           A         B         C          D          E
## a 0.7108047 0.5887064 0.7475385 0.49635015 0.22165474
## b 0.4382942 0.3668981 0.5628502 0.02773473 0.69027218
## c 0.4760304 0.5093910 0.5653860 0.45013939 0.64877213
## d 0.3797047 0.1442291 0.6333318 0.02718772 0.09144519
## e 0.7799683 0.2666545 0.9625866 0.01827093 0.59556958
## f 0.9615772 0.1738209 0.7689412 0.87196248 0.94437824
## g 0.4439984 0.8965273 0.7615242 0.95518889 0.12865765
## h 0.2765765 0.5623431 0.1527221 0.89273842 0.52470189
## i 0.6528749 0.3424543 0.3677980 0.85630873 0.93187571
## j 0.7547240 0.2837297 0.9136158 0.12353308 0.44198207
barplot(x[1:4, ], ylim=c(0, max(x[1:4, ])+0.3), beside=TRUE, legend.text = letters[1:4],
args.legend = list(x = "topleft"))
text(labels=round(as.vector(as.matrix(x[1:4, ])), 2), x=seq(1.5, 21, by=1) +
rep(c(0, 1, 2, 3, 4), each=4), y=as.vector(as.matrix(x[1:4, ]))+0.1)

bar <- barplot(m <- rowMeans(x) * 10, ylim=c(0, 10))
stdev <- sd(t(x[1:4, ]))
arrows(bar, m, bar, m + stdev, length=0.15, angle = 90)

data2 <- read.table('https://umich.instructure.com/files/399129/download?download_frd=1', header=T)
attach(data2)
head(data2)
##   id sex age ses  race traumatype ptsd dissoc service
## 1  1   1   6   0 black   sexabuse    1      1      17
## 2  2   1  14   0 black   sexabuse    0      0      12
## 3  3   0   6   0 black   sexabuse    0      1       9
## 4  4   0  11   0 black   sexabuse    0      1      11
## 5  5   1   7   0 black   sexabuse    1      1      15
## 6  6   0   9   0 black   sexabuse    1      0       6
data2.sub <- data2[, c(-5, -6)]
data2<-data2[, -6]

data2.matrix <- as.data.frame(data2)
Blacks <- data2[which(data2$race=="black"), ]
Other <- data2[which(data2$race=="other"), ]
Hispanic <- data2[which(data2$race=="hispanic"), ]
White <- data2[which(data2$race=="white"), ]
B <- c(mean(Blacks$age), mean(Blacks$service))
O <- c(mean(Other$age), mean(Other$service))
H <- c(mean(Hispanic$age), mean(Hispanic$service))
W <- c(mean(White$age), mean(White$service))
x <- cbind(B, O, H, W)
x
##          B     O    H        W
## [1,] 9.165  9.12 8.67 8.950000
## [2,] 9.930 10.32 9.61 9.911667
bar <- barplot(x, ylim=c(0, max(x)+2.0), beside=TRUE,
legend.text = c("age", "service") , args.legend = list(x = "right"))
text(labels=round(as.vector(as.matrix(x)), 2),
x=seq(1.4, 21, by=1.5), #y=as.vector(as.matrix(x[1:2, ]))+0.3)
y=11.5)
m <- x; stdev <- sd(t(x))
arrows(bar, m, bar, m + stdev, length=0.15, angle = 90)

library(ggplot2)
data2 <- read.table('https://umich.instructure.com/files/399129/download?download_frd=1', header=T)
bar1 <- ggplot(data2, aes(race, fill=race)) + geom_bar()+
facet_grid(. ~ traumatype)
print(bar1)

data3<- read.table("https://umich.instructure.com/files/330385/download?download_frd=1", sep=",", header = TRUE)
head(data3)
##   ID Day Tx SelfEff SelfEff25  WPSS SocSuppt PMss PMss3 PhyAct
## 1  1   1  1      33         8  0.97     5.00 4.03  1.03     53
## 2  1   2  1      33         8 -0.17     3.87 4.03  1.03     73
## 3  1   3  0      33         8  0.81     4.84 4.03  1.03     23
## 4  1   4  0      33         8 -0.41     3.62 4.03  1.03     36
## 5  1   5  1      33         8  0.59     4.62 4.03  1.03     21
## 6  1   6  1      33         8 -1.16     2.87 4.03  1.03      0
hc<-hclust(dist(data3), method='ave')
par (mfrow=c(1, 1))
plot(hc)

require(graphics)
mem <- cutree(hc, k = 10)
# mem; # to print the hierarchical tree labels for each case
# which(mem==5) # to identify which cases belong to class/cluster 5
#To see the number of Subjects in which cluster:
# table(cutree(hc, k=5))

cent <- NULL
for(k in 1:10){
cent <- rbind(cent, colMeans(data3[mem == k, , drop = FALSE]))
}

hc1 <- hclust(dist(cent), method = "ave", members = table(mem))
plot(hc1, hang = -1, main = "Re-start from 10 clusters")

library(corrplot)
## corrplot 0.84 loaded
NC_Associations_Data <- read.table("https://umich.instructure.com/files/330391/download?download_frd=", header=TRUE, row.names=1, sep=",", dec=".")
M <- cor(NC_Associations_Data)
M[1:10, 1:10]
##              P2          P5          P9         P12         P13
## P2   1.00000000 -0.05976123  0.99999944 -0.05976123  0.21245299
## P5  -0.05976123  1.00000000 -0.05976131 -0.02857143  0.56024640
## P9   0.99999944 -0.05976131  1.00000000 -0.05976131  0.21248635
## P12 -0.05976123 -0.02857143 -0.05976131  1.00000000 -0.05096471
## P13  0.21245299  0.56024640  0.21248635 -0.05096471  1.00000000
## P14 -0.05976123  1.00000000 -0.05976131 -0.02857143  0.56024640
## P15 -0.08574886  0.69821536 -0.08574898 -0.04099594  0.36613665
## P16 -0.08574886  0.69821536 -0.08574898 -0.04099594  0.36613665
## P17 -0.05976123 -0.02857143 -0.05976131 -0.02857143 -0.05096471
## P18 -0.05976123 -0.02857143 -0.05976131 -0.02857143 -0.05096471
##             P14         P15         P16         P17         P18
## P2  -0.05976123 -0.08574886 -0.08574886 -0.05976123 -0.05976123
## P5   1.00000000  0.69821536  0.69821536 -0.02857143 -0.02857143
## P9  -0.05976131 -0.08574898 -0.08574898 -0.05976131 -0.05976131
## P12 -0.02857143 -0.04099594 -0.04099594 -0.02857143 -0.02857143
## P13  0.56024640  0.36613665  0.36613665 -0.05096471 -0.05096471
## P14  1.00000000  0.69821536  0.69821536 -0.02857143 -0.02857143
## P15  0.69821536  1.00000000  1.00000000 -0.04099594 -0.04099594
## P16  0.69821536  1.00000000  1.00000000 -0.04099594 -0.04099594
## P17 -0.02857143 -0.04099594 -0.04099594  1.00000000 -0.02857143
## P18 -0.02857143 -0.04099594 -0.04099594 -0.02857143  1.00000000
corrplot(M, method = "circle", title = "circle", tl.cex = 0.5, tl.col = 'black', mar=c(1, 1, 1, 1))

# par specs c(bottom, left, top, right) which gives the margin size specified in inches
corrplot(M, method = "square", title = "square", tl.cex = 0.5, tl.col = 'black', mar=c(1, 1, 1, 1))

corrplot(M, method = "ellipse", title = "ellipse", tl.cex = 0.5, tl.col = 'black', mar=c(1, 1, 1, 1))

corrplot(M, method = "pie", title = "pie", tl.cex = 0.5, tl.col = 'black',
mar=c(1, 1, 1, 1))

corrplot(M, type = "upper", tl.pos = "td",
method = "circle", tl.cex = 0.5, tl.col = 'black',
order = "hclust", diag = FALSE, mar=c(1, 1, 0, 1))

corrplot.mixed(M, number.cex = 0.6, tl.cex = 0.6)

wiki_url <- read_html("http://wiki.socr.umich.edu/index.php/SOCR_Data_Dinov_021708_Earthquakes")
html_nodes(wiki_url, "#content")
## {xml_nodeset (1)}
## [1] <div id="content" class="mw-body-primary" role="main">\n\t<a id="top ...
## {xml_nodeset (1)}
## [1] <div id="content" class="mw-body-primary" role="main">\n\t<a id="top...
earthquake<- html_table(html_nodes(wiki_url, "table")[[2]])

library(ggplot2)
plot4<-ggplot(earthquake, aes(Depth, Latitude, group=Magt, color=Magt))+
geom_line()
print(plot4)

plot5<-ggplot(earthquake, aes(Latitude, group=Magt, newsize=2))+
geom_density(aes(color=Magt), size = 2) +
theme(legend.position = 'right',
legend.text = element_text(color= 'black', size = 12, face = 'bold'),
legend.key = element_rect(size = 0.5, linetype='solid'),
legend.key.size = unit(1.5, 'lines'))
print(plot5)
## Warning: Groups with fewer than two data points have been dropped.

# table(earthquake$Magt) # to see the distribution of magnitude types

kd <- with(MASS::geyser, MASS::kde2d(duration, waiting, n = 50))
kd$x[1:5]
## [1] 0.8333333 0.9275510 1.0217687 1.1159864 1.2102041
kd$y[1:5]
## [1] 43.00000 44.32653 45.65306 46.97959 48.30612
kd$z[1:5, 1:5]
##              [,1]         [,2]         [,3]         [,4]         [,5]
## [1,] 9.068691e-13 4.238943e-12 1.839285e-11 7.415672e-11 2.781459e-10
## [2,] 1.814923e-12 8.473636e-12 3.671290e-11 1.477410e-10 5.528260e-10
## [3,] 3.428664e-12 1.599235e-11 6.920273e-11 2.780463e-10 1.038314e-09
## [4,] 6.114498e-12 2.849475e-11 1.231748e-10 4.942437e-10 1.842547e-09
## [5,] 1.029643e-11 4.793481e-11 2.070127e-10 8.297218e-10 3.088867e-09
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
with(kd, plot_ly(x=x, y=y, z=z, type="surface"))
volcano[1:10, 1:10]
##       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
##  [1,]  100  100  101  101  101  101  101  100  100   100
##  [2,]  101  101  102  102  102  102  102  101  101   101
##  [3,]  102  102  103  103  103  103  103  102  102   102
##  [4,]  103  103  104  104  104  104  104  103  103   103
##  [5,]  104  104  105  105  105  105  105  104  104   103
##  [6,]  105  105  105  106  106  106  106  105  105   104
##  [7,]  105  106  106  107  107  107  107  106  106   105
##  [8,]  106  107  107  108  108  108  108  107  107   106
##  [9,]  107  108  108  109  109  109  109  108  108   107
## [10,]  108  109  109  110  110  110  110  109  109   108
plot_ly(z=volcano, type="surface")
library(jpeg)
# Get an image file downloaded (default: MRI_ImageHematoma.jpg)
img_url <- "https://umich.instructure.com/files/1627149/download?download_frd=1"
img_file <- tempfile(); download.file(img_url, img_file, mode="wb")
img <- readJPEG(img_file)
file.info(img_file)
##                                                                         size
## C:\\Users\\kran0007\\AppData\\Local\\Temp\\RtmpuunS33\\file15d01df23e02 8019
##                                                                         isdir
## C:\\Users\\kran0007\\AppData\\Local\\Temp\\RtmpuunS33\\file15d01df23e02 FALSE
##                                                                         mode
## C:\\Users\\kran0007\\AppData\\Local\\Temp\\RtmpuunS33\\file15d01df23e02  666
##                                                                                       mtime
## C:\\Users\\kran0007\\AppData\\Local\\Temp\\RtmpuunS33\\file15d01df23e02 2019-06-01 22:20:40
##                                                                                       ctime
## C:\\Users\\kran0007\\AppData\\Local\\Temp\\RtmpuunS33\\file15d01df23e02 2019-06-01 22:20:37
##                                                                                       atime
## C:\\Users\\kran0007\\AppData\\Local\\Temp\\RtmpuunS33\\file15d01df23e02 2019-06-01 22:20:40
##                                                                         exe
## C:\\Users\\kran0007\\AppData\\Local\\Temp\\RtmpuunS33\\file15d01df23e02  no
file.remove(img_file) # cleanup
## [1] TRUE
img <- img[, , 1] # extract the first channel (from RGB intensity spectrum) as a univariate 2D array
# package spatstat has a function blur() that applies a Gaussian blur
library(spatstat)
## Loading required package: spatstat.data
## Loading required package: nlme
## Loading required package: rpart
## 
## spatstat 1.59-0       (nickname: 'J'ai omis les oeufs de caille') 
## For an introduction to spatstat, type 'beginner'
## 
## Attaching package: 'spatstat'
## The following object is masked from 'package:gplots':
## 
##     col2hex
img_s <- as.matrix(blur(as.im(img), sigma=10)) # the smoothed version of the image
z2 <- img_s + 1 # abs(rnorm(1, 1, 1)) # Upper confidence surface
z3 <- img_s - 1 # abs(rnorm(1, 1, 1)) # Lower confidence limit
# Plot the image surfaces
p <- plot_ly(z=img, type="surface", showscale=FALSE) %>%
add_trace(z=z2, type="surface", showscale=FALSE, opacity=0.98) %>%
add_trace(z=z3, type="surface", showscale=FALSE, opacity=0.98)
p # Plot the mean-surface along with lower and upper confidence services.
# load data CaseStudy09_HealthBehaviorRisks_Data
data_2 <- read.csv("https://umich.instructure.com/files/602090/download?download_frd=1", sep=",", header = TRUE)

data.raw <- data_2[, -c(1, 14, 17)]

hc = hclust(dist(data.raw), 'ave')

par (mfrow=c(1, 1))
# very simple dendrogram
plot(hc)

summary(data_2$TOTINDA); summary(data_2$RFDRHV4)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    1.00    1.00    1.00    1.56    2.00    9.00
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##     1.0     1.0     1.0     1.3     1.0     9.0
cutree(hc, k = 2)
##    [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##   [35] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##   [69] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [103] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 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1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [613] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [647] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [681] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [715] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [749] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [783] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [817] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [851] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [885] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [919] 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
##  [953] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
##  [987] 2 2 2 2 2 2 2 2 2 2 2 2 2 2
# alternatively specify the height, which is, the value of the criterion associated with the
# clustering method for the particular agglomeration -- cutree(hc, h= 10)
table(cutree(hc, h= 10)) # cluster distribution
## 
##   1   2 
## 930  70
# To identify the number of cases for varying number of clusters we
# can combine calls to cutree and table in a call to sapply -
# to see the sizes of the clusters for $2\ge k \ge 10$ cluster-solutions:
# numbClusters=4;
myClusters = sapply(2:5, function(numbClusters)table(cutree(hc, numbClusters)))
names(myClusters) <- paste("Number of Clusters=", 2:5, sep = "")
myClusters
## $`Number of Clusters=2`
## 
##   1   2 
## 930  70 
## 
## $`Number of Clusters=3`
## 
##   1   2   3 
## 930  50  20 
## 
## $`Number of Clusters=4`
## 
##   1   2   3   4 
## 500 430  50  20 
## 
## $`Number of Clusters=5`
## 
##   1   2   3   4   5 
## 500 430  10  40  20
#To see which SubjectIDs are in which clusters:
table(cutree(hc, k=2))
## 
##   1   2 
## 930  70
groups.k.2 <- cutree(hc, k = 2)
sapply(unique(groups.k.2), function(g)data_2$ID[groups.k.2 == g])
## [[1]]
##   [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
##  [18]  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34
##  [35]  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51
##  [52]  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68
##  [69]  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85
##  [86]  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102
## [103] 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
## [120] 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
## [137] 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
## [154] 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
## [171] 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
## [188] 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
## [205] 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
## [222] 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
## [239] 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
## [256] 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
## [273] 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
## [290] 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
## [307] 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
## [324] 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
## [341] 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
## [358] 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
## [375] 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
## [392] 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
## [409] 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
## [426] 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
## [443] 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
## [460] 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
## [477] 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
## [494] 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
## [511] 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
## [528] 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
## [545] 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
## [562] 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
## [579] 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
## [596] 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
## [613] 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
## [630] 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
## [647] 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
## [664] 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
## [681] 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
## [698] 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
## [715] 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
## [732] 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
## [749] 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
## [766] 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
## [783] 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
## [800] 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
## [817] 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
## [834] 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
## [851] 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
## [868] 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
## [885] 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
## [902] 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
## [919] 919 920 921 922 923 924 925 926 927 928 929 930
## 
## [[2]]
##  [1]  931  932  933  934  935  936  937  938  939  940  941  942  943  944
## [15]  945  946  947  948  949  950  951  952  953  954  955  956  957  958
## [29]  959  960  961  962  963  964  965  966  967  968  969  970  971  972
## [43]  973  974  975  976  977  978  979  980  981  982  983  984  985  986
## [57]  987  988  989  990  991  992  993  994  995  996  997  998  999 1000
groups.k.3 <- cutree(hc, k = 3)
sapply(unique(groups.k.3), function(g)data_2$TOTINDA [groups.k.3 == g])
## [[1]]
##   [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [36] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [71] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [106] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1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9 9 9 9 9 9
# Perhaps there are intrinsically 3 groups here e.g., 1, 2 and 9 .
groups.k.3 <- cutree(hc, k = 3)
sapply(unique(groups.k.3), function(g)data_2$TOTINDA [groups.k.3 == g])
## [[1]]
##   [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [36] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
##  [71] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [106] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [141] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [176] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [211] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [246] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [281] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [316] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [351] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [386] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [421] 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 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [841] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [876] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [911] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 
## [[2]]
##  [1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## [36] 2 2 2 2 2 9 9 9 9 9 9 9 9 9 9
## 
## [[3]]
##  [1] 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
# Note that there is quite a dependence between the outcome variables.
plot(data_2$RFDRHV4, data_2$TOTINDA)

# drill down deeper
table(groups.k.3, data_2$RFDRHV4)
##           
## groups.k.3   1   2   9
##          1 910  20   0
##          2   0  40  10
##          3   0   0  20
aggregate(data_2, list(groups.k.3), median)
##   Group.1    ID AGE_G SEX RACEGR3 IMPEDUC IMPMRTL EMPLOY1 INCOMG CVDINFR4
## 1       1 465.5     5   2       1       5       1       2      4        2
## 2       2 955.5     6   2       4       6       5       8      6        2
## 3       3 990.5     6   2       9       6       6       8      6        2
##   CVDCRHD4 CVDSTRK3 DIABETE3 RFSMOK3 RFDRHV4 FRTLT1 VEGLT1 TOTINDA
## 1      2.0        2        3       1       1      1      1       1
## 2      2.0        2        3       2       2      9      9       2
## 3      4.5        2        4       9       9      9      9       9
library(rvest)
# draw data
wiki_url <- read_html("http://wiki.socr.umich.edu/index.php/SOCR_Data_Dinov_091609_SnP_HomePriceIndex")
hm_price_index<- html_table(html_nodes(wiki_url, "table")[[1]])
head(hm_price_index)
##   Index Year    Month AZ-Phoenix CA-LosAngeles CA-SanDiego CA-SanFrancisco
## 1     1 1991  January      65.26         95.28       83.13           71.17
## 2     2 1991 February      65.29         94.12       81.87           70.27
## 3     3 1991    March      64.60         92.83       80.89           69.56
## 4     4 1991    April      64.35         92.83       80.73           69.46
## 5     5 1991      May      64.37         93.37       81.41           70.13
## 6     6 1991     June      64.88         94.25       82.20           70.83
##   CO-Denver DC-Washington FL-Miami FL-Tampa GA-Atlanta IL-Chicago
## 1     48.67         89.38    79.08    81.75      69.61      70.04
## 2     48.68         88.80    78.55    81.76      69.17      70.50
## 3     48.85         87.59    78.44    81.43      69.05      70.63
## 4     49.20         87.56    78.55    81.46      69.40      71.09
## 5     49.51         88.61    77.95    81.33      69.69      71.36
## 6     50.09         89.28    78.49    81.77      70.14      71.66
##   MA-Boston MI-Detroit MN-Minneapolis NC-Charlotte NV-LasVegas NY-NewYork
## 1     64.97      58.24          64.21        73.32       80.96      74.59
## 2     64.17      57.76          64.20        73.26       81.58      73.69
## 3     63.57      57.63          64.19        72.75       81.65      72.87
## 4     63.35      57.85          64.30        72.88       81.67      72.29
## 5     63.84      58.36          64.75        73.26       82.02      72.63
## 6     64.25      58.90          64.95        73.49       81.91      73.50
##   OH-Cleveland OR-Portland WA-Seattle Composite-10
## 1        68.24       56.53      65.53        78.53
## 2        67.96       56.94      64.60        77.77
## 3        68.18       58.03      64.47        77.00
## 4        69.10       58.39      65.09        76.86
## 5        69.92       58.90      66.03        77.31
## 6        70.55       59.54      66.68        78.02
hm_price_index <- hm_price_index[, c(-2, -3)]
colnames(hm_price_index)[1] <- c('time')
require(reshape)
## Loading required package: reshape
## 
## Attaching package: 'reshape'
## The following object is masked from 'package:plotly':
## 
##     rename
hm_index_melted = melt(hm_price_index, id.vars='time') #a common trick for plot, wide -> long format
ggplot(data=hm_index_melted, aes(x=time, y=value, color=variable)) +
geom_line(size=1.5) + ggtitle("HomePriceIndex:1991-2009")

# Linear regression and predict
hm_price_index$pred = predict(lm(`CA-SanFrancisco` ~ `CA-LosAngeles`,
data=hm_price_index))
ggplot(data=hm_price_index, aes(x = `CA-LosAngeles`)) +
geom_point(aes(y = `CA-SanFrancisco`)) +
geom_line(aes(y = pred), color='Magenta', size=2) +
ggtitle("PredictHomeIndex SF - LA")

require(GGally)
## Loading required package: GGally
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
pairs <- hm_price_index[, 10:15]
head(pairs)
##   GA-Atlanta IL-Chicago MA-Boston MI-Detroit MN-Minneapolis NC-Charlotte
## 1      69.61      70.04     64.97      58.24          64.21        73.32
## 2      69.17      70.50     64.17      57.76          64.20        73.26
## 3      69.05      70.63     63.57      57.63          64.19        72.75
## 4      69.40      71.09     63.35      57.85          64.30        72.88
## 5      69.69      71.36     63.84      58.36          64.75        73.26
## 6      70.14      71.66     64.25      58.90          64.95        73.49
colnames(pairs) <- c("Atlanta", "Chicago", "Boston", "Detroit", "Minneapolis", "Charlotte")
ggpairs(pairs) # you can define the plot design by claim "upper", "lower", "diag" etc.

library(rvest)
require(ggplot2)
#draw data
wiki_url <- read_html("http://wiki.socr.umich.edu/index.php/SOCR_Data_LA_Neighborhoods_Data")
html_nodes(wiki_url, "#content")
## {xml_nodeset (1)}
## [1] <div id="content" class="mw-body-primary" role="main">\n\t<a id="top ...
LA_Nbhd_data <- html_table(html_nodes(wiki_url, "table")[[2]])
#display several lines of data
head(LA_Nbhd_data);
##                  LA_Nbhd Income Schools Diversity Age Homes Vets Asian
## 1        Adams_Normandie  29606     691       0.6  26  0.26 0.05  0.05
## 2                 Arleta  65649     719       0.4  29  0.29 0.07  0.11
## 3      Arlington_Heights  31423     687       0.8  31  0.31 0.05  0.13
## 4        Atwater_Village  53872     762       0.9  34  0.34 0.06  0.20
## 5 Baldwin_Hills/Crenshaw  37948     656       0.4  36  0.36 0.10  0.05
## 6                Bel-Air 208861     924       0.2  46  0.46 0.13  0.08
##   Black Latino White Population Area Longitude Latitude
## 1  0.25   0.62  0.06      31068  0.8 -118.3003 34.03097
## 2  0.02   0.72  0.13      31068  3.1 -118.4300 34.24060
## 3  0.25   0.57  0.05      22106  1.0 -118.3201 34.04361
## 4  0.01   0.51  0.22      14888  1.8 -118.2658 34.12491
## 5  0.71   0.17  0.03      30123  3.0 -118.3667 34.01909
## 6  0.01   0.05  0.83       7928  6.6 -118.4636 34.09615
theme_set(theme_grey())
#treat ggplot as a variable
#When claim "data", we can access its column directly eg"x = Longitude"
plot1 = ggplot(data=LA_Nbhd_data, aes(x=LA_Nbhd_data$Longitude,
y=LA_Nbhd_data$Latitude))
#you can easily add attribute, points, label(eg:text)
plot1 + geom_point(aes(size=Population, fill=LA_Nbhd_data$Income), pch=21,
stroke=0.2, alpha=0.7, color=2)+
geom_text(aes(label=LA_Nbhd_data$LA_Nbhd), size=1.5, hjust=0.5, vjust=2,
check_overlap = T)+ 
  scale_size_area() + scale_fill_distiller(limits=c(range(LA_Nbhd_data$Income)), palette='RdBu', na.value='white', name='Income') +
scale_y_continuous(limits=c(min(LA_Nbhd_data$Latitude), max(LA_Nbhd_data$Latitude))) +
coord_fixed(ratio=1) + ggtitle('LA Neughborhoods Scatter Plot (Location,
Population, Income)')

library(rvest)
wiki_url <- read_html("http://wiki.socr.umich.edu/index.php/SOCR_LetterFrequencyData")
letter<- html_table(html_nodes(wiki_url, "table")[[1]])
summary(letter)
##     Letter             English            French            German       
##  Length:27          Min.   :0.00000   Min.   :0.00000   Min.   :0.00000  
##  Class :character   1st Qu.:0.01000   1st Qu.:0.01000   1st Qu.:0.01000  
##  Mode  :character   Median :0.02000   Median :0.03000   Median :0.03000  
##                     Mean   :0.03667   Mean   :0.03704   Mean   :0.03741  
##                     3rd Qu.:0.06000   3rd Qu.:0.06500   3rd Qu.:0.05500  
##                     Max.   :0.13000   Max.   :0.15000   Max.   :0.17000  
##     Spanish          Portuguese        Esperanto          Italian       
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.00000   Min.   :0.00000  
##  1st Qu.:0.01000   1st Qu.:0.00500   1st Qu.:0.01000   1st Qu.:0.00500  
##  Median :0.03000   Median :0.03000   Median :0.03000   Median :0.03000  
##  Mean   :0.03815   Mean   :0.03778   Mean   :0.03704   Mean   :0.03815  
##  3rd Qu.:0.06000   3rd Qu.:0.05000   3rd Qu.:0.06000   3rd Qu.:0.06000  
##  Max.   :0.14000   Max.   :0.15000   Max.   :0.12000   Max.   :0.12000  
##     Turkish           Swedish            Polish          Toki_Pona      
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.00000   Min.   :0.00000  
##  1st Qu.:0.01000   1st Qu.:0.01000   1st Qu.:0.01500   1st Qu.:0.00000  
##  Median :0.03000   Median :0.03000   Median :0.03000   Median :0.03000  
##  Mean   :0.03667   Mean   :0.03704   Mean   :0.03704   Mean   :0.03704  
##  3rd Qu.:0.05500   3rd Qu.:0.05500   3rd Qu.:0.04500   3rd Qu.:0.05000  
##  Max.   :0.12000   Max.   :0.10000   Max.   :0.20000   Max.   :0.17000  
##      Dutch            Avgerage      
##  Min.   :0.00000   Min.   :0.00000  
##  1st Qu.:0.01000   1st Qu.:0.01000  
##  Median :0.02000   Median :0.03000  
##  Mean   :0.03704   Mean   :0.03741  
##  3rd Qu.:0.06000   3rd Qu.:0.06000  
##  Max.   :0.19000   Max.   :0.12000
head(letter)
##   Letter English French German Spanish Portuguese Esperanto Italian
## 1      a    0.08   0.08   0.07    0.13       0.15      0.12    0.12
## 2      b    0.01   0.01   0.02    0.01       0.01      0.01    0.01
## 3      c    0.03   0.03   0.03    0.05       0.04      0.01    0.05
## 4      d    0.04   0.04   0.05    0.06       0.05      0.03    0.04
## 5      e    0.13   0.15   0.17    0.14       0.13      0.09    0.12
## 6      f    0.02   0.01   0.02    0.01       0.01      0.01    0.01
##   Turkish Swedish Polish Toki_Pona Dutch Avgerage
## 1    0.12    0.09   0.08      0.17  0.07     0.11
## 2    0.03    0.01   0.01      0.00  0.02     0.01
## 3    0.01    0.01   0.04      0.00  0.01     0.03
## 4    0.05    0.05   0.03      0.00  0.06     0.04
## 5    0.09    0.10   0.07      0.07  0.19     0.12
## 6    0.00    0.02   0.00      0.00  0.01     0.01
sum(letter[, -1])
## [1] 13.08
require(reshape)
library(scales)
## 
## Attaching package: 'scales'
## The following object is masked from 'package:spatstat':
## 
##     rescale
dtm = melt(letter[, -14], id.vars = c('Letter'))
p = ggplot(dtm, aes(x = Letter, y = value, fill = variable)) +
geom_bar(position = "fill", stat = "identity") +
scale_y_continuous(labels = percent_format())+ggtitle('Pie Chart')
p
## Warning: Removed 12 rows containing missing values (geom_bar).