Reputation: 2341
I have a vector which looks as follows:
avector <- c("outcome", "city", "year", "as.factor(educ)", "age", "log(area)", "peopleinhouse")
I have second vector which looks like this:
svector <- c("outcome", "educ", "city", "year", "age", "peopleinhouse", "area")
I am looking for a piece of code that automates getting them in the same order. Which order that is is not important.
EDIT: Please note that the solution should keep the vectors intact, with the exception of the order of course.
Obviously simple sorting won't work. I have considered something like:
test <- as.formula(paste(avector[1], paste(avector, collapse = " + "), sep = " ~ "))
all.vars(test)
sort(test)
And then to apply the same sorting to the old vector by index. But I go don't know how to go about this.
Any ideas?
Upvotes: 1
Views: 55
Reputation: 388982
I think your approach is good to create a formula object and use all.vars
. You can use match
and order
to get them in same order as svector
.
test <- as.formula(paste(avector[1],paste(avector,collapse = " + "), sep = " ~ "))
tmp <- all.vars(test)
avector[order(match(tmp, svector))]
#[1] "outcome" "as.factor(educ)" "city" "year" "age" "peopleinhouse" "log(area)"
If all value of svector
will be present in avector
, we can use only match
:
avector[match(svector, tmp)]
Another way to get tmp
is by regex and use the same match
procedure as above.
tmp <- gsub('.*\\(|\\)', '', avector)
Upvotes: 2