switch_cols {quickcode}R Documentation

Switch the index of two columns in a data set

Description

Allows the user to choose precisely which two columns they want to swap places, while optionally preventing some rows within the columns from being altered in the process. Excluded rows within the columns act as anchors that are immune from the switching operation on the selected columns.

Usage

switch_cols(data, col1, col2, keep.rows = NULL)

Arguments

data

dataset object

col1

numeric or character the first column name or number

col2

numeric or character the second column name or number

keep.rows

numeric. row number to keep

Examples


# Example using mtcars
data101 <- mtcars[1:7,]

head(data101) # preview overall data

# task 1: basic result of switching columns 5 and 6
head(switch_cols(data101, 5, 6))

# task 1: basic result of switching columns number 5 and name "gear"
head(switch_cols(data101, 5, "gear"))

# task 1: basic result of switching columns "qsec" and "carb"
head(switch_cols(data101, "qsec", "carb"))


# task 2: switch columns, but retain some rows with the switched columns


# lets exchange some columns, but keep content of row 4, 5 intact
data101[1:6,4:7] # preview the portion that is to be changed
res1 <- switch_cols(data101, col1 = 5, col2 = 6, keep.rows = 4:5) # use column numbers
res1[1:6,4:7] # check result, pay attention to rows 4, 5 of columns 5, 6 as well

data101[1:6,6:11] # preview the portion that is to be changed
res2 <- switch_cols(data101,
col1 = "qsec",
col2 = "carb",
keep.rows = c(1,2,3)) # keep 1, 2, 3
res2[1:6,6:11] # check result


[Package quickcode version 0.9.1 Index]