Question: plotting problem with loop in R

0

smyiz •

**20**wrote:I am trying to calculate the correlation coefficient and prepare distance matrix and draw a plot of clustering. I am stuck in plotting. Here is my script:

```
coef <- function(x,y){
a <- sum(x * y) / sqrt(sum(x)^2 * sum(y)^2)
return(a)
}
distance <- function(X) {
n <- ncol(X)
n <- nrow(X)
distMat <- matrix(0, nrow = n, ncol = n)
for ( i in 1:(n-1) ) {
for ( j in (i+1):n ) {
v1 <- X[ , i]
v2 <- X[ , j]
d <- 1 - coef(v1, v2)
distMat[i, j] <- d
distMat[j, i] <- d
}
}
for ( i in 1:n ) { distMat[i, i] <- 1 }
hr <- hclust(distMat, method="average")
plot <- plot(hr)
return(plot)
}
```

See this https://stackoverflow.com/questions/26034177/r-saving-multiple-ggplots-using-a-for-loop

You need to use

`print`

4.8kwhat is exactly the problem? are you getting an error? no plot is generated?

850I call "dev.off()" and the output reads "null device". the plot is not generated :(

20the function returns the plot, to have it save probably you need to

850Thanks for your reply but I am getting this error: Error in X[, i] : object of type 'closure' is not subsettable

20the error refers to this line

can you tell the outcome of the following:

by the way, in R you can easly use function

coron a full matrix instead of looping, see Correlation matrix ...85020"cor" function wants only these methods: "pearson", "kendall", "spearman", I wanna use uncentered-pearson

20I see, then just use a second variable to get it running. The error is due to using the same variable to loop over the columns and rows leading to going beyond X's dimensions, i.e. by setting up the same value for both loops, X has only 18 columns yet n = 3173 = nrow(X).

850Thanks, but I didn't quite get it. Do you mean I need to change v1 <- X[ , i] to v1 <- distMat[ ,i]

20You should be able to compute that using matrix / vector operations without the loops. Let

`M <- t(X) %*% X`

, Let`z <- diag(M)`

. Then your uncentred`cor`

s should be`M / sqrt(z %*% t(z))`

. !!Written but not tested!!5.1kWhat does %*% do please?

850You could experiment or search: https://www.statmethods.net/advstats/matrix.html

5.1kI think, your formulas equal ( x * y) / sqrt(sum(x)^2 * sum(y)^2. In uncentered correlation, it should be started with sum(x*y)

20I wrote the equation to work with all pairs of columns in one go. The [i, j] entry of

`t(X) %*% X`

is equal to`sum(x[, i] * x[, j])`

5.1kCould you split up your distance computation from your plotting step, so that you can debug why R thinks your

`X`

is a function/closure?5.1k