Skip to main content
3 of 3
edited title

R - Order each matrix inside a list of matrices

I have a list where each element is a matrix, and I want to order each matrix individually

Order a matrix is as easy as this:

data <- data[order(data$value),]

But I am struggling to order a list of matrix individually

I have tried this with some variations:

 for(i in 1:lenght(data)){
 data[i] <- data[i][order(data[i]$value),]
 }

data is the list that contains matrices

I have also tried with apply functions

Some ideas?

Thanks!!

All the code:

#The aim is to show one hospital for each state given an outcome 
#in the posotion num of the ranking, its a learning exercise

rankall <- function(outcome, num = "best"){

if (outcome == "heart attack"){
  col <- 11
}else if(outcome == "heart failure"){
  col <- 17
}else if(outcome == "pneumonia"){
  col <- 23
}else{
  stop("invalid outcome")
}

data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")

data <- data[, c(2, 7,col)]

colnames(data) <- c("Hospital", "State", "value")
data$value <- as.numeric(data$value)
data <- data[complete.cases(data),]
data <- split(data, data$State)

#data2 is the final result dataframe
data2 <- data.frame(matrix(nrow = 0, ncol = 3))
colnames(data2) <- c("Hospital", "State", "value")

#From here is what I do not know how to do it.

#data is a list of matrices, each matrix corresponds to a state
#data2 is the result dataframe, where I am going to add the row num of each 
matrix in data

#1. Order each matrix in data by value and alfabetically if tie
#2. Add to data 2 the row num of each matrix in data once they are sort

for(i in 1:lenght(data)){

data[i] <- data[i][order(data[i]$Hospital),]
data[i] <- data[i][order(data[i]$value),]

if(num =="best"){
  num = 1;
}else if(num == "worst"){
  num = nrow(data[i])
}

num <- as.numeric(num)

rbind(data2,data[i][num])

}

return(data2)

}

Sorry about identations, it changed when I paste the code