R: losing column names when adding rows to an empty data frame

前端 未结 8 1145
旧时难觅i
旧时难觅i 2020-12-05 01:36

I am just starting with R and encountered a strange behaviour: when inserting the first row in an empty data frame, the original column names get lost.

example:

相关标签:
8条回答
  • 2020-12-05 02:13

    You can do this:

    give one row to the initial data frame

     df=data.frame(matrix(nrow=1,ncol=length(newrow))
    

    add your new row and take out the NAS

    newdf=na.omit(rbind(newrow,df))
    

    but watch out that your newrow does not have NAs or it will be erased too.

    Cheers Agus

    0 讨论(0)
  • 2020-12-05 02:14

    The rbind help pages specifies that :

    For ‘cbind’ (‘rbind’), vectors of zero length (including ‘NULL’) are ignored unless the result would have zero rows (columns), for S compatibility. (Zero-extent matrices do not occur in S3 and are not ignored in R.)

    So, in fact, a is ignored in your rbind instruction. Not totally ignored, it seems, because as it is a data frame the rbind function is called as rbind.data.frame :

    rbind.data.frame(c(5,6))
    #  X5 X6
    #1  5  6
    

    Maybe one way to insert the row could be :

    a[nrow(a)+1,] <- c(5,6)
    a
    #  one two
    #1   5   6
    

    But there may be a better way to do it depending on your code.

    0 讨论(0)
提交回复
热议问题