## ----echo=FALSE---------------------------------------------------------------
require(Hmisc)
knitrSet('prostate', width=80)

## ----results='asis'-----------------------------------------------------------
require(Hmisc)
getHdata(prostate)  # Download and make prostate accessible
# Convert an old date format to R format
prostate$sdate <- as.Date(prostate$sdate)
d <- describe(prostate[2:17])
latex(d, file='')

## -----------------------------------------------------------------------------
# Allow only 1 d.f. for three of the predictors
prostate <-
  transform(prostate,
            ekg.norm = 1*(ekg %in% c("normal","benign")),
            rxn = as.numeric(rx),
            pfn = as.numeric(pf))
# Force pfn, rxn to be linear because of difficulty of placing
# knots with so many ties in the data
# Note: all incomplete cases are deleted (inefficient)
redun(~ stage + I(rxn) + age + wt + I(pfn) + hx +
      sbp + dbp + ekg.norm + hg + sz + sg + ap + bm,
      r2=.3, type='adjusted', data=prostate)

## -----------------------------------------------------------------------------
x <- with(prostate,
          cbind(stage, rx, age, wt, pf, hx, sbp, dbp,
                ekg.norm, hg, sz, sg, ap, bm))
# If no missing data, could use cor(apply(x, 2, rank))
r <- rcorr(x, type="spearman")$r    # rcorr in Hmisc
maxabsr <- max(abs(r[row(r) != col(r)]))

## ----spearman,h=3,w=3,bot=-1,top=-.5,right=-.5,xpd=NA,cap=paste('Matrix of Spearman $\\rho$ rank correlation coefficients between predictors.  Horizontal gray scale lines correspond to $\\rho=0$.  The tallest bar corresponds to $|\\rho|=',round(maxabsr,2),'$.',sep=''),scap='Spearman $\\rho$ rank correlations of predictors'----
p <- nrow(r)
plot(c(-.35,p+.5),c(.5,p+.25), type='n', axes=FALSE,
     xlab='',ylab='')   # Figure (*\ref{fig:prostate-spearman}*)
v <- dimnames(r)[[1]]
text(rep(.5,p), 1:p, v, adj=1)
for(i in 1:(p-1)) {
  for(j in (i+1):p) {
    lines(c(i,i),c(j,j+r[i,j]/maxabsr/2),
          lwd=3, lend='butt')
    lines(c(i-.2,i+.2),c(j,j), lwd=1, col=gray(.7))
  }
  text(i, i, v[i], srt=-45, adj=0)
}

## ----hclust,h=2.5,w=4,cap="Hierarchical clustering using Hoeffding's $D$ as a similarity measure.  Dummy variables were used for the categorical variable \\co{ekg}.  Some of the dummy variables cluster together since they are by definition negatively correlated.",scap="'Hierarchical clustering"----
vc <- varclus(~ stage + rxn + age + wt + pfn + hx +
              sbp + dbp + ekg.norm + hg + sz + sg + ap + bm,
              sim='hoeffding', data=prostate)
plot(vc)   # Figure (*\ref{fig:prostate-hclust}\label{pg:ex.varclus.D}*)

## ----transcan,w=6.5,h=5,bot=1,cap='Simultaneous transformation and single imputation of all candidate predictors using \\fu{transcan}.   Imputed values are shown as red plus signs.  Transformed values are arbitrarily scaled to $[0,1]$.',scap='Simultaneous transformation and imputation using \\fu{transcan}'----
# Combine 2 levels of ekg (one had freq. 1)
levels(prostate$ekg)[levels(prostate$ekg) %in%
                     c('old MI', 'recent MI')] <- 'MI'

prostate$pf.coded <- as.integer(prostate$pf)
# make a numeric version; combine last 2 levels of original
levels(prostate$pf) <- levels(prostate$pf)[c(1,2,3,3)]

ptrans <-
  transcan(~ sz + sg + ap + sbp + dbp +
           age + wt + hg + ekg + pf + bm + hx, imputed=TRUE,
           transformed=TRUE, trantab=TRUE, pl=FALSE,
           show.na=TRUE, data=prostate, frac=.1, pr=FALSE)
summary(ptrans, digits=4)
ggplot(ptrans, scale=TRUE) +
  theme(axis.text.x=element_text(size=6))   # Figure (*\ref{fig:prostate-transcan}*)

## ----pc,top=1,w=4,h=3,cap='Variance of the system of raw predictors (black) explained by individual principal components (lines) along with cumulative proportion of variance explained (text), and variance explained by components computed on \\fu{transcan}-transformed variables (red)',scap='Variance of the system explained by principal components.'----
# Impute all missing values in all variables given to transcan
imputed <- impute(ptrans, data=prostate, list.out=TRUE)
imputed <- as.data.frame(imputed)

# Compute principal components on imputed data.
# Create a design matrix from ekg categories
Ekg <- model.matrix(~ ekg, data=imputed)[, -1]
# Use correlation matrix
pfn <- prostate$pfn
prin.raw <- princomp(~ sz + sg + ap + sbp + dbp + age +
                     wt + hg + Ekg + pfn + bm + hx,
                     cor=TRUE, data=imputed)

plot(prin.raw, type='lines', main='', ylim=c(0,3))#Figure (*\ref{fig:prostate-pc}*)
# Add cumulative fraction of variance explained
addscree <- function(x, npcs=min(10, length(x$sdev)),
                     plotv=FALSE,
                     col=1, offset=.8, adj=0, pr=FALSE) {
  vars <- x$sdev^2
  cumv <- cumsum(vars)/sum(vars)
  if(pr) print(cumv)
  text(1:npcs, vars[1:npcs] + offset*par('cxy')[2],
       as.character(round(cumv[1:npcs], 2)),
       srt=45, adj=adj, cex=.65, xpd=NA, col=col)
  if(plotv) lines(1:npcs, vars[1:npcs], type='b', col=col)
}
addscree(prin.raw)
prin.trans <- princomp(ptrans$transformed, cor=TRUE)
addscree(prin.trans, npcs=10, plotv=TRUE, col='red',
         offset=-.8, adj=1)

## ----aic,cap='AIC of Cox models fitted with progressively more principal components.  The solid blue line depicts the AIC of the model with all original covariates.  The dotted blue line is positioned at the AIC of the full spline model.',scap='AIC vs.\ number of principal components',bty="l"----
require(rms)
S <- with(prostate, Surv(dtime, status != "alive"))
# two-column response var.

pcs <- prin.raw$scores         # pick off all PCs
aic <- numeric(16)
for(i in 1:16) {
  ps <- pcs[,1:i]
  aic[i] <- AIC(cph(S ~ ps))
}   # Figure (*\ref{fig:prostate-aic}*)
plot(1:16, aic, xlab='Number of Components Used',
     ylab='AIC', type='l', ylim=c(3950,4000))
f <- cph(S ~ sz + sg + log(ap) + sbp + dbp + age + wt + hg +
         ekg + pf + bm + hx, data=imputed)
abline(h=AIC(f), col='blue')
## The following model in the 2nd edition no longer converges
# f <- cph(S ~ rcs(sz,5) + rcs(sg,5) + rcs(log(ap),5) +
#          rcs(sbp,5) + rcs(dbp,5) + rcs(age,3) + rcs(wt,5) +
#          rcs(hg,5) + ekg + pf + bm + hx,
#          tol=1e-14, data=imputed)
f <- cph(S ~ rcs(sz,4) + rcs(sg,4) + rcs(log(ap),5) +
         rcs(sbp,4) + rcs(dbp,4) + rcs(age,3) + rcs(wt,4) +
         rcs(hg,4) + ekg + pf + bm + hx,
         tol=1e-14, data=imputed)
abline(h=AIC(f), col='blue', lty=2)

## -----------------------------------------------------------------------------
# Compute PC1 on a subset of transcan-transformed predictors
pco <- function(v) {
  f <- princomp(ptrans$transformed[,v], cor=TRUE)
  vars <- f$sdev^2
  cat('Fraction of variance explained by PC1:',
      round(vars[1]/sum(vars),2), '\n')
  f$scores[,1]
}
tumor   <- pco(c('sz','sg','ap','bm'))
bp      <- pco(c('sbp','dbp'))
cardiac <- pco(c('hx','ekg'))
# Get transformed individual variables that are not clustered
other   <- ptrans$transformed[,c('hg','age','pf','wt')]
f <- cph(S ~ tumor + bp + cardiac + other)  # other is matrix
AIC(f)

## ----results='asis'-----------------------------------------------------------
print(f, latex=TRUE, long=FALSE, title='')

## ----spca,cap='Variance explained by individual sparse principal components (lines) along with cumulative proportion of variance explained (text)',scap='Sparse principal components'----
require(pcaPP)
s <- sPCAgrid(ptrans$transformed, k=10, method='sd',
              center=mean, scale=sd, scores=TRUE,
              maxiter=10)
plot(s, type='lines', main='', ylim=c(0,3))   # Figure (*\ref{fig:prostate-spca}*)
addscree(s)
lo <- unclass(s$loadings)
flo <- format(round(lo, 2), zero.print=FALSE)
print(flo, quote=FALSE)    # These loadings are on the orig. transcan scale

## ----spc,cap='Performance of sparse principal components in Cox models',scap='Performance of sparse principal components',bty='l'----
pcs <- s$scores         # pick off sparse PCs
aic <- numeric(10)
for(i in 1:10) {
  ps <- pcs[,1:i]
  aic[i] <- AIC(cph(S ~ ps))
}   # Figure (*\ref{fig:prostate-spc}*)
plot(1:10, aic, xlab='Number of Components Used',
     ylab='AIC', type='l',  ylim=c(3950,4000))

## ----ace,h=4.5,w=6,mfrow=c(4,3),left=-2,cap='Simultaneous transformation of all variables using ACE.',scap='Transformation of variables using ACE'----
x <- with(imputed,
          cbind(sz, sg, ap, sbp, dbp, age, wt, hg, ekg, pf,
                bm, hx))
monotonic <- c("sz","sg","ap","sbp","dbp","age","pf")
transace(x, monotonic,   # Figure (*\ref{fig:prostate-ace}*)
         categorical="ekg", binary=c("bm","hx"))


#Code for calculating the area under curve using Trapezoidal Integration
#Input File has single column containing Values

args <- commandArgs(trailingOnly = TRUE);
raw_data = read.csv(args[1])
data <- cbind(1:dim(raw_data)[1],raw_data)
require(pracma)
AUC = trapz(as.vector(t(data[1])),as.vector(t(data[2])))
disp(AUC)


kbic <- function(x){
###
###  Input: a list of kmeans objects for k=1:K.
###  Output: a vector of BIC_k
###
###  I'm pretty sure there is a better
###  way to code this ...

    K <- length(x)
    bic <- foreach(i = 1:K, .combine=c)%do%{
    kvec <- x[[i]]
    k <- nrow(kvec$centers)
    d <- ncol(kvec$centers)
    n <- length(kvec$cluster)

    sigHat <- 1/(length(kvec$cluster)-i)*kvec$tot.withinss
    lj <- foreach(j = 1:length(kvec$size),.combine=sum)%do%{
        -(kvec$size[j])/2*log(2*pi) -
            (kvec$size[j]*ncol(kvec$centers))/2 *
            log(sigHat) - (kvec$size[j] - i)/2 +
            kvec$size[j] * log(kvec$size[j]) -
            kvec$size[j] * log(length(kvec$cluster))
        }

    pj <- ((k-1) + d*k + 1)
    bic <- lj - pj/2 * log(length(kvec$cluster))
    bic
    }
    return(bic)
}


# 4. faza: Analiza podatkov

#6 Napoved števila igralcev tedna za centre

tabela_centri_vmesno <- igralci_tedna %>% filter(Pozicija == "C")
stetje <- count(tabela_centri_vmesno, Sezona_okrajsano)
tabela_centri <- as.data.frame(stetje)

pril_lm <- lm(data=tabela_centri, n ~ Sezona_okrajsano)
nova_leta <- data.frame(Sezona_okrajsano=seq(2019,2022,1))
napoved <- mutate(nova_leta, n=predict(pril_lm, nova_leta))

graf_napoved <- ggplot(tabela_centri, aes(Sezona_okrajsano,n)) + geom_smooth(method="lm", fullrange=TRUE, alpha = 0.3, color = "dodgerblue2", size = 0.6)+
  geom_point(data=napoved,aes(Sezona_okrajsano,n),color="red", size=2)+ theme_bw() +
  geom_point(color="dodgerblue4", size = 2) + ggtitle("Napoved števila centrov kot igralcev tedna") + xlab("Sezona")+ylab("Število")

#7 Primerjava dveh igralcev

tabela_harden2 <- tabela_harden[,-c(2,3,4,5,6,7,8,9,10,11,13)]
tabela_harden2$Year <- as.numeric(tabela_harden2$Year)
tabela_harden2 <- as.data.frame(tabela_harden2)

pril_lmh <- lm(data=tabela_harden2,P_WEEK ~ Year)
nova_letah <- data.frame(Year=19)
napovedh <- mutate(nova_letah, P_WEEK=predict(pril_lmh,nova_letah))

tabela_curry2 <- tabela_curry[,-c(2,3,4,5,6,7,8,9,10,11,13)]
tabela_curry2$Year <- as.numeric(tabela_curry2$Year)
tabela_curry2 <- as.data.frame(tabela_curry2)

pril_lmc <- lm(data=tabela_curry2,P_WEEK ~ Year)
nova_letac <- data.frame(Year=19)
napovedc <- mutate(nova_letac, P_WEEK=predict(pril_lmc,nova_letac))

pril_lmh2 <- loess(data=tabela_harden2,P_WEEK ~ Year,control=loess.control(surface="direct"))
nova_letah2 <- data.frame(Year=19)
napovedh2 <- mutate(nova_letah2, P_WEEK=predict(pril_lmh2,nova_letah2))

pril_lmc2 <- loess(data=tabela_curry2,P_WEEK ~ Year,control=loess.control(surface="direct"))
nova_letac2 <- data.frame(Year=19)
napovedc2 <- mutate(nova_letac2, P_WEEK=predict(pril_lmc2,nova_letac2))
napovedc2[1,2] <- 0   # Ker vrednost ne more biti manjša od 0

graf_harden_curry2 <- ggplot(data=zdruzena, aes(Year,P_WEEK)) + geom_point(data = zdruzena %>% filter (Name =="Harden"), color="red", size=2.8) +
  geom_smooth(data = zdruzena %>% filter (Name =="Harden"), color="red", fill="indianred1", size=1, alpha = 0.2, method="loess") +
  geom_point(data= zdruzena %>% filter (Name == "Curry"), color = "darkgoldenrod", size =2.8) + theme_bw()+
  geom_smooth(data= zdruzena %>% filter (Name == "Curry"), color = "darkgoldenrod", fill="goldenrod1", size=1, alpha= 0.2, method="loess") +
  geom_point(data=napovedh,aes(Year,P_WEEK), color="tomato",size=6,shape=16)+
  geom_point(data=napovedh,aes(Year,P_WEEK), color="black",size=5,shape=49)+
  geom_point(data=napovedc,aes(Year,P_WEEK), color="goldenrod1",size=6,shape=16)+
  geom_point(data=napovedc,aes(Year,P_WEEK), color="black",size=5,shape=49)+
  geom_point(data=napovedh2, aes(Year, P_WEEK), color="tomato",size=6,shape=16)+
  geom_point(data=napovedh2, aes(Year, P_WEEK), color="black",size=5,shape=50)+
  geom_point(data=napovedc2,aes(Year,P_WEEK), color="goldenrod1",size=6,shape=16)+
  geom_point(data=napovedc2,aes(Year,P_WEEK), color="black",size=5,shape=50)+
  xlab("Sezona") + ylab("Igralec tedna") +
  ggtitle("Primerjava in napoved števila osvojenih nazivov igralca tedna") + theme(legend.position = "right") +
  annotate("text", x=16.8, y=7, label= "James Harden", color="red", size=5) +
  annotate("text",x=14,y=-2,label="Stephen Curry", color="darkgoldenrod", size=5)


=begin
  # sample-quotientfield04.rb

  require "algebra"

  F13 = ResidueClassRing(Integer, 13)
  F = RationalFunctionField(F13, "x")
  x = F.var
  AF = AlgebraicExtensionField(F, "a") {|a| a**2 - 2*x}
  a = AF.var

  p( (a/4*x + AF.unity/2)/(x**2 + a*x + 1) +
    (-a/4*x + AF.unity/2)/(x**2 - a*x + 1) )
  #=> (-x^3 + x^2 + 1)/(x^4 + 11x^3 + 2x^2 + 1)
((<_|CONTENTS>))
=end


# 4. faza: Napredna analiza podatkov

# Razvrscanje najvecjih skupin
# Pri moskih je srednjosolska

Najvecja_skupina_moski <- Starost_Izobrazba_Spol %>% filter(Izobrazba == "SS_moski")

data1 <- Najvecja_skupina_moski %>% select(Leto, Stevilo) %>% as.matrix() %>% scale()
D1 <- dist(data1)
model1 <- hclust(D1)
ddata1 <- dendro_data(model1, type = "rectangle")

ddata1$labels$label<- paste(Najvecja_skupina_moski$Starost[model1$order])
ddata1$labels$Starost <- Najvecja_skupina_moski$Starost[model1$order]

dendogram1 <- ggplot(segment(ddata1)) +
  geom_segment(aes(x = x, y = y, xend = xend, yend = yend )) +
  coord_flip() +
  scale_y_reverse(expand = c(0.2,0)) +
  geom_text(
    data = ddata1$labels,
    aes(x=x, y=y, label=label, color = Starost), hjust=0, size=4, nudge_y = 0.03) +
  theme(
    axis.line.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.text.y = element_blank(),
    axis.title.y = element_blank(),
    panel.background = element_rect(fill = "white"),
    panel.grid = element_blank()
  )

skupine <- cutree(model1, k=3)

razvrstitev1 <- Najvecja_skupina_moski %>%
  ggplot(aes(Leto, Stevilo, col = skupine)) +
  geom_point(size = 4) +
  theme_classic() +
  scale_x_continuous(breaks = seq(2011, 2020, 1))

# Pri zenskah je visjesolska

Najvecja_skupina_zenske <- Starost_Izobrazba_Spol %>% filter(Izobrazba == "VS_zenske")

data2 <- Najvecja_skupina_zenske %>% select(Leto, Stevilo) %>% as.matrix() %>% scale()
D2 <- dist(data2)
model2 <- hclust(D2)
ddata2 <- dendro_data(model2, type = "rectangle")

ddata2$labels$label<- paste(Najvecja_skupina_zenske$Starost[model2$order])
ddata2$labels$Starost <- Najvecja_skupina_zenske$Starost[model2$order]

dendogram2 <- ggplot(segment(ddata2)) +
  geom_segment(aes(x = x, y = y, xend = xend, yend = yend )) +
  coord_flip() +
  scale_y_reverse(expand = c(0.2,0)) +
  geom_text(
    data = ddata2$labels,
    aes(x=x, y=y, label=label, color = Starost), hjust=0, size=4, nudge_y = 0.03) +
  theme(
    axis.line.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.text.y = element_blank(),
    axis.title.y = element_blank(),
    panel.background = element_rect(fill = "white"),
    panel.grid = element_blank()
  )

skupine <- cutree(model2, k=3)

razvrstitev2 <- Najvecja_skupina_zenske %>%
  ggplot(aes(Leto, Stevilo, col = skupine)) +
  geom_point(size = 4) +
  theme_classic() +
  scale_x_continuous(breaks = seq(2011, 2020, 1))

# Napovedni model
# Za mosko populacijo

MA <- function(x, n) stats::filter(x, rep(1/n,n), sides = 1)

data3 <- Najvecja_skupina_moski %>% filter(Starost != "Stari")

napoved1 <- data3 %>%
  ggplot(aes(Leto, Stevilo))+
  geom_point(col = "green", size = 4) +
  stat_smooth(se = TRUE, size = 2) +
  geom_line(aes(Leto, MA(Stevilo, 3)), col = "red", size = 2) +
  theme_classic() +
  scale_x_continuous(breaks = seq(2011, 2022, 1))

# Za zensko populacijo

data4 <- Najvecja_skupina_zenske %>% filter(Starost != "Stari")

napoved2 <- data4 %>%
  ggplot(aes(Leto, Stevilo))+
  geom_point(col = "green", size = 4) +
  stat_smooth(se = TRUE, size = 2) +
  geom_line(aes(Leto, MA(Stevilo, 3)), col = "red", size = 2) +
  theme_classic() +
  scale_x_continuous(breaks = seq(2011, 2022, 1))


permutation.test <- function(treatment, control) {
  perms <- combinations(length(treatment)+length(control),
                        length(treatment),
                        c(treatment, control),
                        set=FALSE)
  p <- mean(rowMeans(perms) <= mean(treatment))
  c(under=p, over=(1-p))
}


total<-0;x<-1:999;for(i in seq(along=x)){if(x[i]%%3==0||x[i]%%5==0){total=total+i;}};total


# install libs
install.packages("readr", dependencies = TRUE)
install.packages("clValid", dependencies = TRUE)
install.packages("mclust", dependencies = TRUE)
install.packages("FactoMineR", dependencies = TRUE)
install.packages("factoextra", dependencies = TRUE)

# load dependences
library(readr)
library(cluster)
library(clValid)
library(mclust)
library(ggplot2)
library(FactoMineR)
library(factoextra)

# load data
points <- read_csv("/home/ghost/MEGAsync/dataset front features/points.csv", col_types = cols(dataset = col_skip(), ethnicity = col_skip(), gender = col_skip()))

# variables
maxitems <- 300000
nclust <- 2:14
clmethods <- c("hierarchical","kmeans","pam")

# prepare data
exprs <- scale(points[,-1])
rownames(exprs) <- points$file[1:546]

#
intern <- clValid(exprs, nClust = nclust, clMethods = clmethods, validation = "internal", maxitems = maxitems)
summary(intern)
plot(intern)
#      4        5        6       7
# 0.7882   0.7839   0.7824   0.7835

###

k <- 4

res.d <- dist(exprs, method="euclidean")
res.hc <- hclust(res.d, method="ward.D2")

# http://www.sthda.com/english/articles/25-cluster-analysis-in-r-practical-guide/111-types-of-clustering-methods-overview-and-quick-start-r-code/

# Hierarchical clustering
# fviz_dend(res.hc, k=k, cex=0.5, palette="jco", color_labels_by_k=TRUE, rect=TRUE)

# Clustering validation statistics
set.seed(123)
res.hc <- eclust(exprs, "hclust", k=k, graph=FALSE)
fviz_dend(res.hc, palette="jco", rect=TRUE, show_labels=FALSE)
fviz_silhouette(res.hc)

# http://www.sthda.com/english/articles/30-advanced-clustering/100-hierarchical-k-means-clustering-optimize-clusters/

#res.hk <-hkmeans(exprs, k)
#names(res.hk)
#fviz_dend(res.hk, cex=0.6, palette="jco", rect=TRUE, rect_border="jco", rect_fill=TRUE, show_labels=FALSE)
#fviz_cluster(res.hk, palette="jco", repel=TRUE, ggtheme=theme_classic(), geom="point")

# http://www.sthda.com/english/articles/22-principal-component-methods/74-hcpc-hierarchical-clustering-on-principal-components/

res.pca <- PCA(exprs, ncp=k, graph=FALSE)
res.hcpc <- HCPC(res.pca, nb.clust=k, graph=FALSE)
#fviz_dend(res.hcpc, show_labels=FALSE, palette="jco", rect=TRUE, rect_fill=TRUE, rect_border="jco", labels_track_height=0.8)
fviz_cluster(res.hcpc, repel=TRUE, show.clust.cent=TRUE, palette="jco", ggtheme=theme_minimal(), main="Factor map", geom="point")
plot(res.hcpc, choice="3D.map")

#groups <- cutree(res.hc, k=k)

points$cluster<-res.hc$cluster
rownames<-c("la","lb","lc","ld","le","lf","lg","lh","ra","rb","rc","rd","re","rf","rg","rh")
mainDir<-paste("/home/ghost/MEGAsync/dataset front features/k", k, sep="")
ifelse(!dir.exists(mainDir), dir.create(mainDir), FALSE)
#allPoints<-NULL
par(bg=NA)
for (i in 1:nrow(points)){
  file<-points[i,]$file

  clusterDir<-paste(mainDir, "/c", points[i,]$cluster, sep="")
  ifelse(!dir.exists(clusterDir), dir.create(clusterDir), FALSE)

  leftDir<-paste(clusterDir, "-l", sep="")
  ifelse(!dir.exists(leftDir), dir.create(leftDir), FALSE)

  rightDir<-paste(clusterDir, "-r", sep="")
  ifelse(!dir.exists(rightDir), dir.create(rightDir), FALSE)

  onlyPoints<-points[i, 2:33]

  odd<-onlyPoints[,seq(1,ncol(onlyPoints),2)]
  odd<-t(odd)
  colnames(odd)<-c("x")
  rownames(odd)<-rownames

  even<-onlyPoints[,seq(2,ncol(onlyPoints),2)]
  even<-t(even)
  colnames(even)<-c("y")
  rownames(even)<-rownames

  newPoints=cbind(odd,even)
  write.csv(newPoints, file = paste(clusterDir, "/", file, ".csv", sep=""))

  write.csv(newPoints[1:8,], file = paste(leftDir, "/", file, ".csv", sep=""))
  left<-rbind(newPoints[1:8,],newPoints[1,])
  png(paste(leftDir, "/", file, ".png", sep=""))
  plot(left, type="o", lty="dashed",  axes=FALSE, xlab="", ylab="")
  dev.off()

  write.csv(newPoints[9:16,], file = paste(rightDir, "/", file, ".csv", sep=""))
  right<-rbind(newPoints[9:16,],newPoints[9,])
  png(paste(rightDir, "/", file, ".png", sep=""))
  plot(right, type="o", lty="dashed",  axes=FALSE, xlab="", ylab="")
  dev.off()

  #allPoints<-rbind(allPoints,newPoints)
}
#png(paste(clusterDir, "/cluster.png", sep=""))
#plot(allPoints, type="p", axes=FALSE, xlab="", ylab="")
#dev.off()

points <- read_csv("/home/vinicius/MEGAsync/dataset front features/k4")

only_points<-points[1, 2:33]

odd<-only_points[,seq(1,ncol(only_points),2)]
odd<-t(odd)
colnames(odd)<-c("x")
rownames(odd)<-rownames

even<-only_points[,seq(2,ncol(only_points),2)]
even<-t(even)
colnames(even)<-c("y")
rownames(even)<-rownames

new_points=cbind(odd,even)

left=rbind(new_points[1:8,],new_points[1,])
right=rbind(new_points[9:16,],new_points[9,])
plot(right, type="o", lty="dashed",  axes=FALSE, xlab="", ylab="")