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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With