0
I’m doing an exercise* for my R studies and I’m not able to properly manipulate matrices. The problem is very simple, apparently.
I have a matrix’m'
m <- rbind( c(1,1), c(1,2), c(3,3), c(2,0))
,
and simply want to take the value in each of the positions. In this case, wanted to store the vector (1,1)
in a variable, then the (1,2)
and so on. The ultimate goal is to use each vector of the matrix and perform the calculation of the distance between the point x
and that vector.
I couldn’t do it in any automated way by going through all the positions. Someone can help?
Complete Code:
get_neighbor <- function(x, m, k){
for(len in 1:dim(m)[len]){
len <- len
}
if (k > len){
return("The k is higher than ...")
}
else{
for(i in 1:len){
m <- m[1]
print(m)
}
d <- sqrt(sum((x - m)^2))
cat("The distance is", d, "\n")
}
}
len <- 1
i <- 1
x <- c(0,2)
m <- rbind( c(1,1), c(1,2), c(3,3), c(2,0))
get_neighbor(x, m, 1)
(It was not I who voted down) 1) In
for(len in 1:dim(m)[len])
, how is it thatlen
is the variable that indexesdim(.)
if it is not yet defined; 2) And by the way, how many dimensions it hasm
? 3) What does the instructionlen <- len
ago?– Rui Barradas