7

I have a list of data frames which I need to obtain the last row of the 2nd column from. All the data frames have differing number of rows. I've already written code using lapply which can extract any row by variable "num" (returning NA for numbers which exceed the row length of the data frames) , however I want to include a variable num="worst" which will return the last row, 2nd column of available data. This is the code to retrive the "nth" row (xyz is the list of data frames):

if(num=="best"){num=as.integer(1)} else
(num=as.integer())

rownumber<-lapply(xyz, "[", num, 2, drop=FALSE)

Been cracking my head all day trying to find a solution to declare num=="worst". I want to avoid loops hence my use of lapply, but perhaps there is no other way?

4

2 回答 2

17

怎么样...

lapply(xyz, tail, 1)
于 2013-10-17T17:42:22.427 回答
2

data.frame我对这个问题的理解是,您需要一个从数据帧中返回 a 的第二列的函数,list并带有一个可选参数worst,允许您将其限制为最后一次观察。

我认为最简单的方法是编写一个辅助函数,然后使用lapply.

我编写了一个selector函数,它接受一个行和列参数以及一个worst参数。我认为这可以满足您的一切需求。

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)
于 2013-10-17T18:33:08.163 回答