Ali
Ali

Reputation: 11

How to extract the last row of the first column in each group in a list?

I have been trying to write a function that could extract the Hotel Name with the worst mortality rate in each state. Below I noted the code I have tried, but the output does not match with the correct answer.

state_data <- state_data[order(state_data$State, state_data$Deaths),]
state_data <- split(state_data, state_data$State)
output <- do.call(rbind, lapply(state_data, function(x) {
  c(x[nrow(x), 1], x[1, 2]) ## x[1,2] returns the state name
}))
data.frame(output)  

I am sure there are other ways to do it, but I wonder why I cannot get the accurate result with the code above. Would appreciate any help!

Upvotes: 1

Views: 305

Answers (1)

akrun
akrun

Reputation: 887048

An option would be to extract the first column with [[ and get the last element with tail

sapply(state_data, function(x) tail(x[[1]], 1))

Or using dplyr on the up splitted dataset

library(dplyr)
state_data %>%
    group_by(State) %>%
    select(1) %>%
    slice(n())

Upvotes: 2

Related Questions