Creating an R dataframe row-by-row

后端 未结 8 802
天涯浪人
天涯浪人 2020-11-29 15:52

I would like to construct a dataframe row-by-row in R. I\'ve done some searching, and all I came up with is the suggestion to create an empty list, keep a list index scalar,

8条回答
  •  甜味超标
    2020-11-29 16:19

    If you have vectors destined to become rows, concatenate them using c(), pass them to a matrix row-by-row, and convert that matrix to a dataframe.

    For example, rows

    dummydata1=c(2002,10,1,12.00,101,426340.0,4411238.0,3598.0,0.92,57.77,4.80,238.29,-9.9)
    dummydata2=c(2002,10,2,12.00,101,426340.0,4411238.0,3598.0,-3.02,78.77,-9999.00,-99.0,-9.9)
    dummydata3=c(2002,10,8,12.00,101,426340.0,4411238.0,3598.0,-5.02,88.77,-9999.00,-99.0,-9.9)
    

    can be converted to a data frame thus:

    dummyset=c(dummydata1,dummydata2,dummydata3)
    col.len=length(dummydata1)
    dummytable=data.frame(matrix(data=dummyset,ncol=col.len,byrow=TRUE))
    

    Admittedly, I see 2 major limitations: (1) this only works with single-mode data, and (2) you must know your final # columns for this to work (i.e., I'm assuming that you're not working with a ragged array whose greatest row length is unknown a priori).

    This solution seems simple, but from my experience with type conversions in R, I'm sure it creates new challenges down-the-line. Can anyone comment on this?

提交回复
热议问题