1

Here is my dataset.

set.seed (1234) mydf <- data.frame (Id = c("dis", 1:5), V1.a = c(0,sample(c(0, 1,2), 5, replace = T)),V1.b = c(0,sample(c(0, 1,2), 5, replace = T)), V2.a = c(1.5,sample(c(0, 1,2), 5, replace = T)),V2.b = c(1.5,sample(c(0, 1,2), 5, replace = T)), V3.a = c(2.0,sample(c(0, 1,2), 5, replace = T)),V3.b = c(2.0,sample(c(0, 1,2), 5, replace = T)), V4.a = c(5.0,sample(c(0, 1,2), 5, replace = T)),V4.b = c(5.0,sample(c(0, 1,2), 5, replace = T)), V5.a = c(6.0,sample(c(0, 1,2), 5, replace = T)),V5.b = c(6.0,sample(c(0, 1,2), 5, replace = T)), V16a = c(11.0,sample(c(0, 1,2), 5, replace = T)),V6.b = c(11.0,sample(c(0, 1,2), 5, replace = T)), V7.a = c(12.0,sample(c(0, 1,2), 5, replace = T)),V7.b = c(12.0,sample(c(0, 1,2), 5, replace = T)), V8.a = c(3.0,sample(c(0, 1,2), 5, replace = T)),V8.b = c(3.0,sample(c(0, 1,2), 5, replace = T))) d = mydf > d Id V1.a V1.b V2.a V2.b V3.a V3.b V4.a V4.b V5.a V5.b V16a V6.b V7.a V7.b V8.a 1 0 0 0 1.5 1.5 2 2 5 5 6 6 11 11 12 12 3 2 1 1 2 1.0 0.0 1 2 1 2 0 1 1 2 0 1 1 3 2 1 1 2.0 2.0 1 2 0 1 0 1 1 1 0 2 0 4 3 0 0 1.0 2.0 2 0 2 2 2 2 2 1 1 2 0 5 4 0 2 0.0 2.0 2 2 1 1 2 2 2 1 2 1 0 6 5 2 1 2.0 0.0 2 0 1 1 0 1 0 0 0 2 1 V8.b 1 3 2 2 3 0 4 2 5 0 6 2 

I wanted to order by value in first row element of each variable.

> d <- d[,order(d[1,-1])] > d Id V1.a V1.b V2.a V2.b V3.a V7.b V8.a V3.b V4.a V4.b V5.a V5.b V16a V6.b V7.a 1 0 0 0 1.5 1.5 2 12 3 2 5 5 6 6 11 11 12 2 1 1 2 1.0 0.0 1 1 1 2 1 2 0 1 1 2 0 3 2 1 1 2.0 2.0 1 2 0 2 0 1 0 1 1 1 0 4 3 0 0 1.0 2.0 2 2 0 0 2 2 2 2 2 1 1 5 4 0 2 0.0 2.0 2 1 0 2 1 1 2 2 2 1 2 6 5 2 1 2.0 0.0 2 2 1 0 1 1 0 1 0 0 0 

Ordering is not working for V7.a! V8.a is missing. What is the problem or good way to do it some other way?

1 Answer 1

4

The integer vector returned by order(d[1,-1]) refers to the data.frame d[,-1] (i.e. d with the first column removed). If you then use that vector to index the columns in d, you get a meaningless sorting of its columns (and you lose the final column altogether).

This should fix the problem:

d[,c(1, 1+ order(d[1,-1]))] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.