Print the last line from the list of data frames

I have a list of data frames that I need to get from the last row of the second column. All data frames have a different number of rows. I already wrote the code using lapply, which can extract any row of the variable "num" (returning NA for numbers that exceed the length of the row of data frames), however I want to include the variable num = "worst", which will return the last row, the second column available data. This is the code to extract the string "nth" (xyz is a list of data frames):

if(num=="best"){num=as.integer(1)} else (num=as.integer()) rownumber<-lapply(xyz, "[", num, 2, drop=FALSE) 

I cracked my head all day trying to find a solution to declare num == "worst." I want to avoid loops, so my use is latent, but maybe there is no other way?

+7
r lapply
source share
2 answers

My understanding of the question is that you need a function that returns the second column data.frame from the list data, with the optional worst argument, which allows you to limit it to the last observation.

I think the easiest way to do this is to write a helper function and then apply it to your list with lapply .

I wrote a selector function that takes a row and column argument, as well as the worst argument. I think this does everything you need.

 df1 <- data.frame(A = rnorm(10), B = rnorm(10), C = rnorm(10)) df2 <- data.frame(A = rnorm(10), B = rnorm(10), C = rnorm(10)) ldf <- list(df1, df2) selector <- function(DF, col, row=NULL, worst=FALSE){ if(!is.null(row)) return(DF[row, col]) if(!missing("col")) if(col > ncol(DF)) return(NA) if(!is.null(row)) if(row > nrow(DF)) return(NA) if(worst) { tail(DF[,col, drop=F],1) } else { DF[row, col, drop=FALSE] } } lapply(ldf, selector, worst=T) 
+2
source share

What about...

 lapply(xyz, tail, 1) 
+14
source share

All Articles