简体   繁体   中英

checking every two adjacent elements in rows of a matrix

I'm new to coding in R, perhaps my question maybe too easy.

I have a matrix "data" of dimension 299*5992. Each element is either A1 or A2 so I want to concentrate information of the matrix like this:

XD=matrix(,dim(data)[1],(dim(data)[2])/2 )
for ( i in dim(XD)[1])
{
  for (j in dim(XD)[2])
  {
    if (data[i,2*j]==data[i,2*j-1])
    {XD[i,j]=-1}
    else
    {XD[i,j]=1
    }
  }
}  

So I have 2 questions:

  1. How to do this more efficiently?
  2. When I call an element like XD[1,1] I get NA even though I'm sure that matrix data is loaded correctly.

Here is a way with only one sapply loop.

Make up some data.

set.seed(1234)
data <- matrix(sample(c("A1", "A2"), 96, TRUE), 8)

And compute the matrix XD .

XD <- sapply(seq(1, ncol(data), by = 2), function(j){
  2*(data[, j] == data[, j + 1]) - 1
})

Here are two approaches to make it:

  • Solution 1 (I believe this one is the more efficient one than the latter)

You can use first get logical value by comparing two adjacent columns and then shape it into the desired matrix, where ifelse is used:

M <- matrix(ifelse(data[,seq(ncol(data))%%2==1]==data[,seq(ncol(data))%%2==0],-1,1),
            nrow = nrow(data))

which gives

> M
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,]    1    1    1   -1    1   -1    1    1   -1     1     1     1     1    -1     1    -1
[2,]    1    1    1    1    1   -1    1   -1   -1    -1    -1    -1    -1    -1     1     1
[3,]   -1   -1    1   -1    1    1    1   -1   -1    -1    -1    -1    -1    -1    -1    -1
[4,]   -1    1   -1    1    1   -1   -1    1    1    -1     1    -1    -1     1    -1     1
  • Solution 2

Besides the solution by @Rui Barradas , you can also use sapply along with split.default and data.frame as below

M <- sapply(split.default(data.frame(data,stringsAsFactors = F),rep(1:(dim(data)[2]/2),1,each=2)),
                          function(v) ifelse(v[1]==v[2],-1,1))

which gives

> M
      1  2  3  4 5  6  7  8  9 10 11 12 13 14 15 16
[1,]  1  1  1 -1 1 -1  1  1 -1  1  1  1  1 -1  1 -1
[2,]  1  1  1  1 1 -1  1 -1 -1 -1 -1 -1 -1 -1  1  1
[3,] -1 -1  1 -1 1  1  1 -1 -1 -1 -1 -1 -1 -1 -1 -1
[4,] -1  1 -1  1 1 -1 -1  1  1 -1  1 -1 -1  1 -1  1

DATA

set.seed(1)
data <- matrix(sample(c("A1", "A2"), 128, TRUE), 4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM