Oscar Kjell
Oscar Kjell

Reputation: 1651

R sort columns alphabetically in each dataframe of a list of dataframes

I want to sort each column alphabetically in every dataframe of a list of dataframe.

Example data:

A <-  c(1, 2, 3, 4)
B <-  c(1, 2, 3, 4)
C <-  c(1, 2, 3, 4)

df1 <- tibble(B, C, A)
df2<- tibble(C, B, A)

list_df1_2 <- list(df1, df2)
list_df1_2

# For example tried
list_df1_2_ordered <- purrr::map(list_df1_2, function(.x) order(colnames(x)))

Upvotes: 1

Views: 508

Answers (2)

akrun
akrun

Reputation: 887231

With tidyverse, we can wrap the order within select

library(dplyr)
library(purrr)
list_df1_2 <- map(list_df1_2, ~ .x %>%
               select(order(names(.))))

-output

list_df1_2
#[[1]]
# A tibble: 4 x 3
#      A     B     C
#  <dbl> <dbl> <dbl>
#1     1     1     1
#2     2     2     2
#3     3     3     3
#4     4     4     4

#[[2]]
# A tibble: 4 x 3
#      A     B     C
#  <dbl> <dbl> <dbl>
#1     1     1     1
#2     2     2     2
#3     3     3     3
#4     4     4     4

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521569

For a base R option, you may use lapply on your list and then sort the columns of each data frame by column name:

list_df1_2 <- lapply(list_df1_2, function(x) x[ , order(names(x))])

Upvotes: 3

Related Questions