rdatasculptor
rdatasculptor

Reputation: 8447

how to put variables in the right order using a vector with ordering cues?

I am generating dataframes with different amounts of variables, which are in the wrong positions most of the time.

e.g. this dataframe

df <-   structure(list(A = c(1, 2, 3, 4, 5), F = c(5, 4, 3, 2, 1), D = c(5, 
    5, 4, 4, 1)), .Names = c("A", "F", "D"), row.names = c(NA, 5L
    ), class = "data.frame")


  A F D
1 1 5 5
2 2 4 5
3 3 3 4
4 4 2 4
5 5 1 1

I have a vector that helps me knowing what the right order should be, e.g.:

c("A","B","C","D","E","F")

How can I use this vector put, programmatically my generated dataframes in the right order?

According to the vector, this should be the result:

  A D F
1 1 5 5
2 2 5 4
3 3 4 3
4 4 4 2
5 5 1 1

Any ideas? most welcome!

Upvotes: 1

Views: 43

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

intersect should work for this:

df[intersect(colorder, names(df))]
#   A D F
# 1 1 5 5
# 2 2 5 4
# 3 3 4 3
# 4 4 4 2
# 5 5 1 1

Upvotes: 3

Related Questions