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!