set specific order of rows for all dataframes within a list

Viewed 21

I have a list of dataframes (about 30). I want to change the order of the rows within these dataframes to a specific order. I have made a small example to illustrate my problem

df1 <-
  data.frame(
    stof = c("CO2", "nh3", "so2", "ch4", "pm10", "pm5"),
    auto = c(1, 2, 3, 6, 2, 3),
    boat = c(4, 5, 6, 7, 5, 5)
  )
df2 <-
  data.frame(
    stof = c("CO2", "nh3", "so2", "ch4", "pm10", "pm5"),
    auto = c(3, 2, 1, 8, 8, 6),
    boat = c(6, 5, 4, 3 , 1 , 2)
  )
l <- list(df1, df2)

I want to reorder based on a specific order for the values in column "stof". I want to do this after I have made the list, not before. The order should be: "pm5", "ch4", "CO2", "so2", "pm10", "nh3"

1 Answers

You can use lapply to apply a function over a list. Here, you need to do two things.

  1. Convert stof to factor, and add a levels arguments with the levels as you want them sorted.

  2. order your data set according to the variable stof

lapply(l, function(x){
  x[["stof"]] <- factor(x[["stof"]], levels = c("pm5", "ch4", "CO2", "so2", "pm10", "nh3"))
  x[order(x[["stof"]]), ]
})

output

[[1]]
  stof auto boat
6  pm5    3    5
4  ch4    6    7
1  CO2    1    4
3  so2    3    6
5 pm10    2    5
2  nh3    2    5

[[2]]
  stof auto boat
6  pm5    6    2
4  ch4    8    3
1  CO2    3    6
3  so2    1    4
5 pm10    8    1
2  nh3    2    5
Related