Create a Data Frame of Unequal Lengths

后端 未结 5 1196
再見小時候
再見小時候 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:20

    Sorry this isn't exactly what you asked, but I think there may be another way to get what you want.

    First, if the vectors are different lengths, the data isn't really tabular, is it? How about just save it to different CSV files? You might also try ascii formats that allow storing multiple objects (json, XML).

    If you feel the data really is tabular, you could pad on NAs:

    > x = 1:5
    > y = 1:12
    > max.len = max(length(x), length(y))
    > x = c(x, rep(NA, max.len - length(x)))
    > y = c(y, rep(NA, max.len - length(y)))
    > x
     [1]  1  2  3  4  5 NA NA NA NA NA NA NA
    > y
     [1]  1  2  3  4  5  6  7  8  9 10 11 12
    

    If you absolutely must make a data.frame with unequal columns you could subvert the check, at your own peril:

    > x = 1:5
    > y = 1:12
    > df = list(x=x, y=y)
    > attributes(df) = list(names = names(df),
        row.names=1:max(length(x), length(y)), class='data.frame')
    > df
          x  y
    1     1  1
    2     2  2
    3     3  3
    4     4  4
    5     5  5
    6    6
    7    7
     [ reached getOption("max.print") -- omitted 5 rows ]]
    Warning message:
    In format.data.frame(x, digits = digits, na.encode = FALSE) :
      corrupt data frame: columns will be truncated or padded with NAs
    

提交回复
热议问题