Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap rows, per two rows

Tags:

r

swap

Is it possible to swap two adjacent rows with each other, and then move onto the next two rows, and swap their individual rows together? i.e. swap col1 value in row 1 with col 1 value in row2; swap col 1700 value in row 87 with col 1700 value in row 88.

sample data:

     col1  col2
row1 a      b
row2 b      b
row3 c      a
row4 d      c

My real data has many rows and columns and the data changes each time I go through a loop, so I need a way where I don't refer to specific column names and row names.

The desired result would look like:

    col1  col2
row1 b      b
row2 a      b
row3 d      c
row4 c      a
like image 812
Gotmadstacks Avatar asked Mar 12 '26 17:03

Gotmadstacks


1 Answers

Add 1 to the first row in a group of 2, subtract one from the second row in a group of 2:

dat[seq_len(nrow(dat)) + c(1,-1),]
#     col1 col2
#row2    b    b
#row1    a    b
#row4    d    c
#row3    c    a

This works because of the vector recycling in R:

1:10 + c(1,-1)
#[1]  2  1  4  3  6  5  8  7 10  9
like image 93
thelatemail Avatar answered Mar 14 '26 09:03

thelatemail