How can I reorder the columns so that I can get "pre" first followed by "post" and then alternating again? Each "pre" and "post" entry is related to a question from a survey. So for example, both the first "pre" and "post" are answers for question 1 of a survey. I want to compare the answers from "pre" and "post" and for organizational purposes, want to know how I can get the column to show pre first then pro and then alternate in that order. thanks!
Fake data:
dat <- data.frame(Time = rep(c("Post","Pre"), 3), Num = 1:6)
dat
# Time Num
# 1 Post 1
# 2 Pre 2
# 3 Post 3
# 4 Pre 4
# 5 Post 5
# 6 Pre 6
I suggest you should always encode the question number in the data so that you can order them arbitrarily throughout your analysis. Never rely on the order of rows to be meaningful and preserved when not immediately discernible in a column or combination of columns.
The additional column:
dat$QuestionNumber <- rep(1:(nrow(dat)/2), each = 2)
dat
# Time Num QuestionNumber
# 1 Post 1 1
# 2 Pre 2 1
# 3 Post 3 2
# 4 Pre 4 2
# 5 Post 5 3
# 6 Pre 6 3
Unfortunately, one cannot use negatives in ordering strings, so the use of match
is a quick hack:
dat[order(dat$QuestionNumber, -match(dat$Time, sort(unique(dat$Time)))),]
# Time Num QuestionNumber
# 2 Pre 2 1
# 1 Post 1 1
# 4 Pre 4 2
# 3 Post 3 2
# 6 Pre 6 3
# 5 Post 5 3
Alternatively, you can use the "radix" ordering method and supply per-column decreasing=
arguments.
dat[order(dat$QuestionNumber, dat$Time, method = "radix", decreasing = c(FALSE, TRUE)),]
# Time Num QuestionNumber
# 2 Pre 2 1
# 1 Post 1 1
# 4 Pre 4 2
# 3 Post 3 2
# 6 Pre 6 3
# 5 Post 5 3
If you really must avoid keeping question number in there, then we can internalize the QuestionNumber
logic into the order
call, even though it can make it a bit difficult to see what's going on.
dat$QuestionNumber <- NULL
dat[order(rep(1:(nrow(dat)/2), each = 2), dat$Time,
method = "radix", decreasing = c(FALSE, TRUE)),]
# Time Num
# 2 Pre 2
# 1 Post 1
# 4 Pre 4
# 3 Post 3
# 6 Pre 6
# 5 Post 5