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

前端 未结 8 1157
旧时难觅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: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.

提交回复
热议问题