elliot elliot - 1 month ago 12
R Question

Best approach to using for loops to reorder columns in a list of dataframes?

I've got a list of dataframes, and I am trying to change the order of the columns. I have the exact error message when I run this example using mtcars:

cyl.4 <- mtcars %>% filter(cyl==4) %>% select(mpg,carb,gear)
cyl.5 <- mtcars %>% filter(cyl==5) %>% select(mpg,carb,gear)

x <- list(cyl.4,cyl.5)

for (i in seq_along(x)){
names(x[[i]]) <- x[c(2,1,3)]
}


I'm new to R and programming, so please forgive this novice question. I've been struggling for a while, and I'd like to use other for loops to do similar data cleaning. I can't find a previously asked question on reordering columns in lists of dataframes. I've also tried to use the purrr package, but it's a bit too advanced for me. Thanks

Answer Source

In your current code, x[c(2,1,3)] is a data.frame: you don't want to use that to provide columns names. Also, you don't want to use names()<- that would only rename columns but reorder them.

You can try:

cyl.4 <- mtcars %>% filter(cyl==4) %>% select(mpg,carb,gear)
cyl.5 <- mtcars %>% filter(cyl==5) %>% select(mpg,carb,gear)

x <- list(cyl.4,cyl.5)

for (i in seq_along(x)){
  x[[i]] <- x[[i]][c(2,1,3)]
}