How to sort a table

Hi there,

that might be a really simple question, but we are completely clueless how to answer it.

We have two tables, one column of each table contains the same variables, but in different order. We want to sort the second table in such a way that it matches the order in the first one. I hope it gets a little bit clearer with the following illustration:

grafik

EDIT: Instead of X2 = 12 in the right table it should be "X2 = 4.3"

Does someone has an idea how to do it in R?

Thank you and best regards,
Alexander

Hi there,

assuming that the
X data in your second table are unique,
everything is in data.table
and that you have 4.3 instead of 12 in your rightiest table

I would suggest the use of rownames

rownames(dt2)<-dt2$X
Sorted_dt2<-dt2[as.vector(dt1$X),]
rownames(dt2)<-NULL
rownames(Sorted_dt2)<-NULL

They're might be something else, but it should work

I think this would just be a left_join in dplyr. It isn't apparent from the example data how the first table is ordered so I've assumed it has been set by something else:

t1 <- tibble::tribble(
    ~X,  ~Y,
    "X2",  12,
    "X3", 8.2,
    "X1",   1
  )

t2 <- tibble::tribble(
  ~X,  ~Y,
  "X1",   1.0,
  "X3", 8.2,
  "X2", 4.3
)

The following code joins the tables and drops the Y column from the first table as it's not included in the select(). Also note that the columns become Y.x and Y.y in the join because they are the same name. I've renamed it back to Y but this might not be an issue in your real data:

library(dplyr)

new_output <- t1 %>% 
  left_join(t2, by = "X") %>% 
  select(X,
         Y = Y.y)

Output:

# A tibble: 3 x 2
  X         Y
  <chr> <dbl>
1 X2      4.3
2 X3      8.2
3 X1      1  

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.