简体   繁体   中英

How to keep columns when converting list to data frame

I am trying to convert a list to a data frame, while keeping the variable names, and the minimum and maximum values in 3 separate columns. I have tried as.data.frame() and have tried to unlist the list, but it creates just one column or it returns the variable type. I am using the nycflights2013 data in R. How would I go about doing this?

checker <- function(x){
if(is.numeric(x)){
  max.x <- max(x, na.rm = TRUE)
  min.x <- min(x, na.rm = TRUE)
  vectorlist <- list(max=max.x, min=min.x)
 return(vectorlist)
 }
else
  vectorlist <- list(max = "NA", min = "NA")
 return(vectorlist)
}
flightlist <- t(sapply(flights, checker))
flightlist
as.data.frame(flightlist)

This works i think, just change how many rows you have:

df <- data.frame(matrix(unlist(flightlist), nrow=100, byrow=T))

Not sure it will retain the colnames, so you could do colnames(df)<- <cols from data>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM