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:
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:
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
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.