0

I'm trying to sort a list filled with 5 different dataframes but with same column names, but just of different arrangements.

Reproducible Example:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6), y3 = c(5,6,7))
d2 <- data.frame(y2 = c(3, 2, 1), y3 = c(6, 5, 4), y1 = c(5,6,7))

my.list <- list(d1, d2)

> my.list
[[1]]
  y1 y2 y3
1  1  4  5
2  2  5  6
3  3  6  7

[[2]]
  y2 y3 y1
1  3  6  5
2  2  5  6
3  1  4  7 

I'm trying to arrange each dataframe columns within the list into a specific order that I have already created under colnamesvec (see below.)

colnamesvec <- c("y3", "y2", "y1")

If I subset out each individual dataframe, I am able to achieve it using base R command. But is there a better way to loop through this easily to achieve what I want?

s <- my.list[[1]]
s[colnamesvec]

Thank you!

0

1 Answer 1

2

Use lapply and reorder the columns for each dataframe.

my.list[] <- lapply(my.list, function(x) x[colnamesvec])


my.list
#[[1]]
#  y3 y2 y1
#1  5  4  1
#2  6  5  2
#3  7  6  3

#[[2]]
#  y3 y2 y1
#1  6  3  5
#2  5  2  6
#3  4  1  7

This is assuming that all the columns in colnamesvec is present in each dataframe in the list.

Sign up to request clarification or add additional context in comments.

3 Comments

@RonakShah Sorry, noticed your post too late. There is some overlap with the linked post but it's not an exact duplicate; shall I re-open?
@MauritsEvers yes, imo it isn't an exact duplicate but I do have a feeling that there must be a post somewhere for this question, couldn't find though.
@RonakShah Ok, I've re-opened; if you find a more closely related post you can close it again. It does feel like one of those "asked-before" questions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.