Swap values among columns of a data frame
swap(data, which)
a data frame
a formula or an integer or character vector specifying columns in
data
swap
is not a particularly speedy function. It is intended primarily
as an aid for teaching randomization for paired designs. Used this way, the number of
randomizations should be kept modest (approximately 1000) unless you are very patient.
if (require(tidyr)) {
Sleep2 <- sleep |> spread( key=group, val=extra )
names(Sleep2) <- c("subject", "drug1", "drug2")
swap(Sleep2, drug1 ~ drug2)
mean( ~(drug1 - drug2), data=Sleep2)
do(3) * mean( ~(drug1 - drug2), data=Sleep2 |> swap(drug1 ~ drug2) )
}
#> Loading required package: tidyr
#>
#> Attaching package: ‘tidyr’
#> The following objects are masked from ‘package:Matrix’:
#>
#> expand, pack, unpack
#> The following object is masked from ‘package:testthat’:
#>
#> matches
#> Using parallel package.
#> * Set seed with set.rseed().
#> * Disable this message with options(`mosaic:parallelMessage` = FALSE)
#> Using parallel package.
#> * Set seed with set.rseed().
#> * Disable this message with options(`mosaic:parallelMessage` = FALSE)
#> Using parallel package.
#> * Set seed with set.rseed().
#> * Disable this message with options(`mosaic:parallelMessage` = FALSE)
#> mean
#> 1 0.32
#> 2 0.16
#> 3 0.90