Create a Data Frame of Unequal Lengths

后端 未结 5 1187
再見小時候
再見小時候 2020-11-29 03:23

While data frame columns must have the same number rows, is there any way to create a data frame of unequal lengths. I\'m not interested in saving them as separate elements

5条回答
  •  离开以前
    2020-11-29 04:00

    Another approach to the padding:

    na.pad <- function(x,len){
        x[1:len]
    }
    
    makePaddedDataFrame <- function(l,...){
        maxlen <- max(sapply(l,length))
        data.frame(lapply(l,na.pad,len=maxlen),...)
    }
    
    x = c(rep("one",2))
    y = c(rep("two",10))
    z = c(rep("three",5))
    
    makePaddedDataFrame(list(x=x,y=y,z=z))
    

    The na.pad() function exploits the fact that R will automatically pad a vector with NAs if you try to index non-existent elements.

    makePaddedDataFrame() just finds the longest one and pads the rest up to a matching length.

提交回复
热议问题