Name variable via a loop R

Multi tool use
Multi tool use


Name variable via a loop R



I'm currently working on a function that will return distance between a point and p clusters.


which_cluster<-function(coord){
cluster<-get_cluster(data) # return a matrix
nbr_clusters=nrow(cluster)
nbr_dim=ncol(cluster)
liste<-c()

for(i in 1:nbr_clusters){
dist_c_i=0
for (j in nbr_dim){
paste('vec_', i, sep = '')
dim_j_c_i=cluster[i,j]
dist_c_i<-dist_c_i+ (dim_j_c_i-coord[i])^2
}
dist_c_i<-sqrt(dist_c_i)
liste<-liste[,dist_c_i]
}

return(liste)
}



I want the "i" and "j" in the variable name to be recognize as the i and j of the for loop.



Thank you for your help. Go easy on me, I'm a beginner ;)





Hi! Could you provide a sample of your data?
– Riverarodrigoa
Jun 28 at 13:20





And an example of the output you are expecting
– emilliman5
Jun 28 at 13:29





get_cluster(data) returns a matrix that contains the position of clusters' center : Dim 1 Dim 2 Dim 3 Dim 4 Dim 5 1 -0.2421963 -0.02219216 1.1548797 6.187503558 4.01138314 2 1.8136751 7.89237995 -0.1976802 1.029745037 -1.66337555 3 0.5433915 -0.20207333 -0.1827094 -0.003705857 -0.02186797 4 -1.0740043 0.17493668 0.3216816 -0.184568336 -0.02079380
– K. Youce
Jun 28 at 13:41





2 Answers
2



Use assign() after paste0():


assign()


paste0()


assign(paste0("dim_", j, "_c_", i), cluster[i,j])





And get(paste0("dim_",j,"_c_",i) when on the right side of a <-. But wouldn't it be better to use a two dimensional array 'dim_' instead? Operations on strings and recognizition of associated symbol will be considerably more expensive.
– Nicolas2
Jun 28 at 13:32






Thnak you for your comment, The matrix I use is not big. maximum 5 columns et 5 rows, that is why I didnt care using 2 "for loops".
– K. Youce
Jun 28 at 13:40





@K. Youce. I wasn't thinking about memory consumption but about speed. Also your code will be a bit cryptic for other readers. When you need indexing you use vectors and arrays not collections of variables. Did you work with SAS before that?
– Nicolas2
Jun 28 at 13:49





No never. I've been learning R for a week now. This code is made to get euclidien distance
– K. Youce
Jun 28 at 14:23






And this is probably the slowest possible way of handling a matrix...
– Anony-Mousse
Jun 30 at 9:27



Don't.



Declaring excessive amounts of variables is slow, and unmanageable.



Instead, use lists and matrixes.



As you seem to try to do a distance matrix, store it as a matrix, indexed by I and j, i.e. dist[i,j].


dist[i,j]






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

LzC7EeX26IMk1nQzaK0gteL,NP,lB BhJ63XXP,VGpevPnjrFxunrBT r c,BJu,78QqjRg4 xf2ictRF
57P9a5Ykg7Jtmj7nSV8,ZGb N kidWdko,fi5w3fm 7ZArAG x40h8TBrgvUGFfv nu

Popular posts from this blog

Delphi Android file open failure with API 26

.

Amasya