Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort pairs of columns in R while keeping associated values together

Tags:

dataframe

r

I'm trying to create a ranked table where I need to sort each pair of columns by the second column in each pair. The first column in each pair needs to stay with its corresponding value. How can I do this in a concise/easy way?

df <- data.frame(
  State1 = c("Ak", "Al", "Az"),
  Value1 = c(1, 10, 30),
  State2 = c("Ak", "Al", "Az"),
  Value2 = c(45, 3, 20))

I want the final output to look like this:

  State1 Value1 State2 Value2
      Az     30     Ak     45
      Al     10     Az     20
      Ak      1     Al      3

like image 447
bandcar Avatar asked Dec 22 '25 06:12

bandcar


1 Answers

A hack would be to first split the data frames into two, reorder their numeric columns, and then merge them back into one data frame like so:

library(dplyr)

df <- data.frame(
  State1 = c("Ak", "Al", "Az"),
  Value1 = c(1, 10, 30),
  State2 = c("Ak", "Al", "Az"),
  Value2 = c(45, 3, 20))

df1 <- df[,c("State1","Value1")]


df2 <- df[,c("State2","Value2")]

df1 <- df1 |> 
  arrange(desc(Value1))

df2 <- df2 |> 
  arrange(desc(Value2))


df_merge <- cbind(df1,df2)


df_merge

  State1 Value1 State2 Value2
1     Az     30     Ak     45
2     Al     10     Az     20
3     Ak      1     Al      3

Hope this helps!

like image 112
Ifeanyi Idiaye Avatar answered Dec 23 '25 21:12

Ifeanyi Idiaye