Allows the user to choose precisely which two rows they want to swap places, while optionally preventing some columns from being altered in the process. Excluded columns within the rows act as anchors that are immune from the switching operation on the selected rows.
Arguments
- data
dataset object
- row1
numeric. the first row number
- row2
numeric. the second row number
- keep.cols
numeric or character. column number or name to keep
Examples
# Example using mtcars
data100 <- mtcars[1:7,]
head(data100) # preview overall data
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
#> Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
# task 1: basic result of switching rows 5 and 6
head(switch_rows(data100, 5, 6))
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
#> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# task 2: switch rows, but retain some columns
data100[5:6,2:10] # preview the portion that is to be changed
#> cyl disp hp drat wt qsec vs am gear
#> Hornet Sportabout 8 360 175 3.15 3.44 17.02 0 0 3
#> Valiant 6 225 105 2.76 3.46 20.22 1 0 3
# lets switch 2 rows, but keep content of columns 7, 8, 9 10 within the changed rows
res1 <- switch_rows(data100, row1 = 5, row2 = 6, keep.cols = 7:10) # use column numbers
res1[5:6,] # check result, pay attention to columns 9 and 10 as well
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Valiant 18.1 6 225 105 2.76 3.46 17.02 0 0 3 1
#> Hornet Sportabout 18.7 8 360 175 3.15 3.44 20.22 1 0 3 2
res2 <- switch_rows(data100,
row1 = 5,
row2 = 6,
keep.cols = c("disp","cyl")) # use column names
res2[5:6,] # check result, pay attention to columns "disp","cyl" as well
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Valiant 18.1 8 360 105 2.76 3.46 20.22 1 0 3 1
#> Hornet Sportabout 18.7 6 225 175 3.15 3.44 17.02 0 0 3 2