Function to move a variable to a different position in a data frame.

mvvar(var, where, after=TRUE, data)

Arguments

var

variable to move.

where

variable next to which var will be moved.

after

logical indicating whether to position var after or before variable where (default is after=TRUE).

data

data frame that contains the variables specified above.

Details

The function can be used to move a variable to a different position in a data frame.

Value

A data frame.

Author

Wolfgang Viechtbauer wvb@wvbauer.com

Examples

# illustrative dataset
dat <- data.frame(subj=rep(1:4, each=5),
                  obs = 1:5,
                  age = rep(c(20,31,27,22), each=5),
                  stress = c(2,3,1,4,2, 3,3,3,3,3, 1,1,2,6,4, 1,2,1,3,1))
dat
#>    subj obs age stress
#> 1     1   1  20      2
#> 2     1   2  20      3
#> 3     1   3  20      1
#> 4     1   4  20      4
#> 5     1   5  20      2
#> 6     2   1  31      3
#> 7     2   2  31      3
#> 8     2   3  31      3
#> 9     2   4  31      3
#> 10    2   5  31      3
#> 11    3   1  27      1
#> 12    3   2  27      1
#> 13    3   3  27      2
#> 14    3   4  27      6
#> 15    3   5  27      4
#> 16    4   1  22      1
#> 17    4   2  22      2
#> 18    4   3  22      1
#> 19    4   4  22      3
#> 20    4   5  22      1

# move variable age after subj
dat <- mvvar("age", "subj", data=dat)
dat
#>    subj age obs stress
#> 1     1  20   1      2
#> 2     1  20   2      3
#> 3     1  20   3      1
#> 4     1  20   4      4
#> 5     1  20   5      2
#> 6     2  31   1      3
#> 7     2  31   2      3
#> 8     2  31   3      3
#> 9     2  31   4      3
#> 10    2  31   5      3
#> 11    3  27   1      1
#> 12    3  27   2      1
#> 13    3  27   3      2
#> 14    3  27   4      6
#> 15    3  27   5      4
#> 16    4  22   1      1
#> 17    4  22   2      2
#> 18    4  22   3      1
#> 19    4  22   4      3
#> 20    4  22   5      1

# move variable obs before age
dat <- mvvar("obs", "age", after=FALSE, data=dat)
dat
#>    subj obs age stress
#> 1     1   1  20      2
#> 2     1   2  20      3
#> 3     1   3  20      1
#> 4     1   4  20      4
#> 5     1   5  20      2
#> 6     2   1  31      3
#> 7     2   2  31      3
#> 8     2   3  31      3
#> 9     2   4  31      3
#> 10    2   5  31      3
#> 11    3   1  27      1
#> 12    3   2  27      1
#> 13    3   3  27      2
#> 14    3   4  27      6
#> 15    3   5  27      4
#> 16    4   1  22      1
#> 17    4   2  22      2
#> 18    4   3  22      1
#> 19    4   4  22      3
#> 20    4   5  22      1