JJFord3
JJFord3

Reputation: 1985

How to order a data frame using a string vector with the names of the columns to be ordered?

Lets assume the data looks like this:

df3 = data.frame(matrix(rnorm(20), nrow=10))
df3$ACCT_ID <- as.numeric(rownames(df3))
df3$X3 <- ifelse(df3$X2 < 1,"LOW","HIGH")

df3
           X1          X2 ACCT_ID   X3
1   0.8533321  0.73676965       1  LOW
2  -0.2289266 -0.87010747       2  LOW
3  -0.7997897  0.49979417       3  LOW
4   0.5281416 -0.70161594       4  LOW
5  -0.6246283  0.81879826       5  LOW
6   0.9939673 -1.20910819       6  LOW
7  -0.8955201  0.42167923       7 HIGH
8   1.4404649  0.59220989       8  LOW
9  -0.8687570  0.09393659       9  LOW
10 -0.7030129 -0.95184303      10  LOW

I'm trying to re-order based on X1 and ACCT_ID.

TEMP_X_DF <- df3[with(df3, order(X1,ACCT_ID)), ]
TEMP_X_DF
           X1          X2 ACCT_ID   X3
7  -0.8955201  0.42167923       7 HIGH
9  -0.8687570  0.09393659       9  LOW
3  -0.7997897  0.49979417       3  LOW
10 -0.7030129 -0.95184303      10  LOW
5  -0.6246283  0.81879826       5  LOW
2  -0.2289266 -0.87010747       2  LOW
4   0.5281416 -0.70161594       4  LOW
1   0.8533321  0.73676965       1  LOW
6   0.9939673 -1.20910819       6  LOW
8   1.4404649  0.59220989       8  LOW

But when I try to do this when populating from a list I only get the first row read in returned:

  IDS <- c("X1","ACCT_ID")
  for (id in 1:length(IDS)){
    if (id == 1){
      ID_OUT <- IDS[id]
    }
    else {
      ID_OUT <- paste(ID_OUT,IDS[id],sep=",")
    }
  }
  TEMP_X_DF <- df3[with(df3, order(ID_OUT)), ]
  TEMP_X_DF
         X1        X2 ACCT_ID  X3
1 0.8533321 0.7367696       1 LOW

Is the string ID_OUT not resolving properly?

Upvotes: 0

Views: 35

Answers (2)

989
989

Reputation: 12937

You could do this using get:

df3[with(df3, order(get(IDS))), ]

You should not concatenate the column names as you did in ID_OUT. Instead, you can put the desired column names in a vector and then apply get.

Upvotes: 2

JJFord3
JJFord3

Reputation: 1985

I found one answer that seems to work well (though I need to know how many columns are listed in the IDS list and to make it more adaptable I ended up putting a couple of quick if statements together).

IDS <- c("X1","ACCT_ID")
if (length(IDS) == 1){
  TEMP_X_DF <- df3[order(df3[,IDS[1]]), ]
}
else if (length(IDS) == 2){
  TEMP_X_DF <- df3[order(df3[,IDS[1]],df3[,IDS[2]]), ]
}
.
.
.

Upvotes: 0

Related Questions