Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

r - Extract Consecutive Pairs of Elements from a Vector and Place in a Matrix

This may be a simple question but I can not find how to produce pairs of values from a vector sequentially which each pair includes last value and new value in a matrix of values with two columns. Example below

C<-c(1 , 20 , 44 , 62 , 64 , 89 , 91, 100)

matrix example

newpairs
     [,1] [,2]
[1,]    1   20
[2,]   20   44
[3,]   44   64
[4,]   64   89
[5,]   89   91
[6,]   91  100

So when I try the matrix it does not work as last element is not repated with the new element

newpairs <- matrix(C, ncol=2, byrow=TRUE) 

newpairs

     [,1] [,2]
[1,]    1   20
[2,]   44   62
[3,]   64   89
[4,]   91  100

I guess you can subset but if C values change then you have to change the drop or keep of subset. I also have tried on functions that extract certain increments or that can extract every nth elemen. However I would like to find a systematic way to create the first example matrix.

Any help is welcomed

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This fits your desired output:

cbind(C[-length(C)], C[-1])
     [,1] [,2]
[1,]    1   20
[2,]   20   44
[3,]   44   62
[4,]   62   64
[5,]   64   89
[6,]   89   91
[7,]   91  100

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...