invalid subscript type 'list'

Viewed 573

Code for reproducible example:

lst1 <- c('a', 'b', 'c', 'd', 'e', 'f')
lst2 <- round(runif(6, min = 5, max = 12),4)
lst3 <- round(runif(6, min = 6, max = 30),4)
lst4 <- round(runif(6, min = 7, max = 28),4)
lst5 <- round(runif(6, min = 4, max = 25),4)

df1 <- data.frame('st' = lst1, 'value' = lst2)
df2 <- data.frame('st' = lst1, 'value' = lst3)
df3 <- data.frame('st' = lst1, 'value' = lst4)
df4 <- data.frame('st' = lst1, 'value' = lst5)

dfList <- list(df1, df2, df3, df4)

Problem statement: Order the specific column of the data frame which is in the list of data frames
I am using for loop like below:

dfRanked <- list()
for (df in dfList){
    dfRanked[[df]] <- df[order(df$value, decreasing = FALSE), ]
}

Its produce error:

Error in dfRanked[[df]] <- df[order(df$value, decreasing = FALSE), ] : 
  invalid subscript type 'list'
1 Answers

Your iterator df in the for loop is a data frame. So dfRanked[[df]] doesn't make sense. You are asking it to subset a list based on a list (data.frame). I think you are looking for something like this.

dfRanked <- dfList

for (i in seq_along(dfRanked)){
  dfRanked[[i]] <- dfRanked[[i]][order(dfRanked[[i]]$value, decreasing = FALSE), ]
}

Alternatively, this should do the same thing but a bit more concisely. This will iterate over each element and apply the function each time.

lapply(dfList, function(df) df[order(df$value, decreasing = FALSE), ])

And finally in tidyverse speak, you can do something like this.

library(dplyr)
library(purrr)

map(dfList, arrange, value)
Related