Lak
Lak

Reputation: 1

Sorting data frame by character string

I have a data frame and need to sort its columns by a character string.

I tried it like this:

  # character string
  a <- c("B", "E", "A", "D", "C")

  # data frame
  data <- data.frame(A = c(0, 0, 1), B = c(1, 1, 1), C = c(1, 0, 1), D = c(0, 0, 1), E = c(0, 1, 1))
  data
  # A B C D E
  # 1 0 1 1 0 0
  # 2 0 1 0 0 1
  # 3 1 1 1 1 1

  # sorting 
  data.sorted <- data[, order(a)]

  # order of characters in data
  colnames(data.sorted)
  # [1] "C" "A" "E" "D" "B"

However, the order of columns in the sorted data frame is not the same as the characters in the original character string.

Is there any way, how to sort it?

Upvotes: 0

Views: 1454

Answers (2)

BarkleyBG
BarkleyBG

Reputation: 664

The function order(a) returns the position in the vector a that each ranked value lies in. So, since "A" (ranked first) lies in the third position of a, a[1] is equal to 3. Similarly "C" (ranked third) lies in the fifth position of a, then a[3] equals 5.

Luckily your solution is actually even more simple, thanks to the way R works with brackets. If you ask to see just the column named "B" you'll get:

> data[, "B", drop=FALSE]
  B
1 1
2 1
3 1

Or if you want two specific columns

> data[, c("B", "E")]
  B E
1 1 0
2 1 1
3 1 1

And finally, more generally, if you have a whole vector by which you want to order your columns, then you can do that, too:

> data.sorted <- data[, a]

> data.sorted
  B E A D C
1 1 0 0 0 1
2 1 1 0 0 0
3 1 1 1 1 1

> all(colnames(data.sorted)==a)
[1] TRUE

Upvotes: 3

shashikant birajdar
shashikant birajdar

Reputation: 1

string[] str = { "H", "G", "F", "D", "S","A" };
Array.Sort(str);
for (int i = 0; i < str.Length; i++)
{
    Console.WriteLine(str[i]);
}
Console.ReadLine();

Upvotes: 0

Related Questions