Vassilis Chasiotis
Vassilis Chasiotis

Reputation: 439

How to reverse specific ranges of a vector at the same time in R?

For example, I have the matrix A, which is the following:

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

Using the code:

Y=unique(A[,3:4])
YY=list()
q=0
for( i in 1:nrow(Y) )
{
a=which(apply(A, 1, function(x) identical(x[3:4], Y[i,])))
if( length(a)>1 )
{
q=q+1
YY[[q]]=a
}}

I obtain the ranges of columns 3 and 4 of matrix A, that have the same elememts. That is, the list Y is:

YY
[[1]]
[1] 1 2 3 4 5 6 7
[[2]]
[1]  8  9 10 11
[[3]]
[1] 12 13 14 15
[[4]]
[1] 16 17 18 19

So, let say I have the vector x=c(1,1,1,1,1,1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1). The desired reversion of x, due to list YY, is the following: c(-1,1,1,1,1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,-1).

The point is to success reversing of a vector for as many ranges as may I have at the same time.

NOTE THAT THE RANGES AND THE NUMBER OF THEM CAN CHANGE.

I tried to use rev() with apply(), but it does not work.

Any ideas?

Upvotes: 0

Views: 188

Answers (1)

niko
niko

Reputation: 5281

Try

x[unlist(sapply(YY, rev))]

The dependence on YY is implemented here and the orders will vary accordingly whenever YY varies.

Upvotes: 1

Related Questions