Search code examples
rmatrixcellapply

R cell selection using apply


i'm trying to select specific cell from a matrix (data) a change the value to 1

i got those 2 vector

data <- matrix(0,300,300)
X <- c(1,5,87,987,67)
Y <- c(5,7,12,456,99)

x1 and y1 (i.e 1,5) indicate the position i want to select in my matrix

I dont want to select (x1,y2)

I have done what i want to do with:

for (i in 1:length(x)){
  data[x[i],y[i]]<-1
}


i'm pretty sure i can do the same thing with apply which could work faster

Thanks for your help


Solution

  • cbind X and Y and assign the value

    data[cbind(X, Y)]  <- 1
    
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]    0    1    0    0    0
    #[2,]    0    0    0    0    0
    #[3,]    0    0    1    0    0
    #[4,]    0    0    0    1    0
    #[5,]    0    0    0    0    0
    

    data

    Using smaller dataset

    X <- c(1,3,4)
    Y <- c(2,3,4)
    data <- matrix(0, ncol = 5, nrow = 5)
    
    data
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]    0    0    0    0    0
    #[2,]    0    0    0    0    0
    #[3,]    0    0    0    0    0
    #[4,]    0    0    0    0    0
    #[5,]    0    0    0    0    0