Picking a vector within an R matrix

Asked

Viewed 39 times

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.

inserir a descrição da imagem aqui

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 that lenis the variable that indexes dim(.) if it is not yet defined; 2) And by the way, how many dimensions it has m? 3) What does the instruction len <- len ago?

2 answers

2

I wouldn’t do it this way, but correcting your solution:

get_neighbor <- function(x, m, k){
  len <- dim(m)[1]

  if (k > len){
    return("The k is higher than ...")
  }
  else{
    for(i in 1:len){
      m1 <- m[i, ]
      d <- sqrt(sum((x - m1)^2))
      cat("The distance is", d, "\n")
    }
  }
}

x <- c(0,2)
m <- rbind( c(1,1), c(1,2), c(3,3), c(2,0))
k <- 4

get_neighbor(x, m, k)

> The distance is 1.414214 
> The distance is 1 
> The distance is 3.162278 
> The distance is 2.828427 

In R, the most simplified would be:

dist(rbind(x,m))[1:dim(m)[1]]
[1] 1.414214 1.000000 3.162278 2.828427
  • How would you do it, Daniel? I tried this approach because it seems to be the one requested by the teacher. Anyway, I liked your solution. Thank you so much for your help!

2

The function below uses only one cycle apply, the rest is vectored.

get_neighbor <- function(x, m, k){
  # função auxiliar
  dist_xy <- function(x, y) sqrt(sum((x - y)^2))
  
  # verificar se k é válido
  # em primeiro lugar, tem que ser positivo
  if(k < 1){
    warning("k is not positive, returning NULL.")
    return( invisible(NULL) )
  }
  
  # em segundo lugar, não pode ser maior que o
  # número de linhas da matriz 'm'
  if(k > nrow(m)){
    mname <- deparse(substitute(m))
    msg <- sprintf("k is larger than the rows of %s.", mname)
    message(msg)
    return( invisible(NULL) )
  }
  
  # agora determinar o k-ésimo vizinho mais próximo
  # 'd' são as distâncias das linhas da matriz a 'x'
  d <- apply(m, 1, dist_xy, x)
  # qual das distâncias é a k-ésima?
  i <- match(k, order(d))
  # é essa que queremos
  m[i, ]
}


x <- c(0,2)
m <- rbind( c(1,1), c(1,2), c(3,3), c(2,0))

get_neighbor(x, m, 1)
#[1] 1 2
get_neighbor(x, m, 2)
#[1] 1 1
get_neighbor(x, m, 3)
#[1] 2 0
get_neighbor(x, m, 4)
#[1] 3 3

get_neighbor(x, m, 10)
#k is larger than the rows of m.

get_neighbor(x, m, -1)
#Warning message:
#In get_neighbor(x, m, -1) : k is not positive, returning NULL.
  • Thank you very much, Rui! I understood perfectly what I was wrong. Saved me too much, thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.