I wrote a code for dbscan algorithm. when I call a function in main It doesnt work and I dont know why
here is the code
x=read.delim("C:/Users/mf/Desktop/stp.txt")
y=read.delim("C:/Users/mf/Desktop/stp.txt")
hash=0
c=temp1=0
q=1
C=0
eps=30
MinPts=30
lable=matrix(-2,1,nrow(x))
clusterlab=matrix(-3,1,nrow(x))
for(p in 1:nrow(x))
{
if(lable[p]==-2)
{
lable[p]=1 #visited=1 and nonvisited=-2
NeighborPts = regionQuery(p, eps)
temp=nrow(NeighborPts)-1
if (temp < MinPts){
clusterlab[p]=0 #noise = 0
}
else if(temp>=MinPts){
C = C+1
haha=expandCluster(p, NeighborPts, C, eps, MinPts,hash,clusterlab,lable)
}
}
}
expandCluster <- function(p, NeighborPts, C, eps, MinPts,hash,clusterlab,lable) {
hash=hash+1
clusterlab[p]=C
for (q in 2:nrow(NeighborPts))
{ testP=NeighborPts[q,1]
if(lable[testP]==-2)
lable[testP]=1
newNeighborPts = regionQuery(testP, eps)
if ((nrow(newNeighborPts)-1) >= MinPts)
NeighborPts = rbind(NeighborPts,newNeighborPts)
if(clusterlab[testP]==-3) #is not yet member of any cluster
clusterlab[testP]=C
}
return(hash)
}
regionQuery <- function(p, eps) {
neighborhood=p
for(i in 1:nrow(x)){
temp=sqrt((x[p,1]-y[i,1])^2+(x[p,2]-y[i,2])^2)
if(temp<eps){
c=c+1
neighborhood=rbind(neighborhood,i)}
}
#neighborhood=neighborhood[-1,]
return(neighborhood)
}
when I call
haha=expandCluster(p, NeighborPts, C, eps, MinPts,hash,clusterlab,lable)
It doesnt work!!
I add hash variable to check it. every time that expancdCLuster called hash must incease. but it doesned increased.
lable and clusterlab is not change too.
data is here
Functions in R are usually designed to pass parameters by value and not by reference. Updating the value of the variables passed in will not change them in the calling environment. Generally speaking, the R way to do this is for your function to return the updated data. If you want to return more than one updated variable, you can use a list
to do this.
You will see people using the assign to parent environment operator (<<-
) and even assign
to the global environment within functions. This style of coding works, but it goes against the principle that functions generally don't modify the calling environment and may make debugging and integrating different pieces of code into a larger project much harder.