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

前端 未结 8 1149
旧时难觅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 01:57

    Instead of constructing the data.frame with numeric(0) I use as.numeric(0).

    a<-data.frame(one=as.numeric(0), two=as.numeric(0))
    

    This creates an extra initial row

    a
    #    one two
    #1   0   0
    

    Bind the additional rows

    a<-rbind(a,c(5,6))
    a
    #    one two
    #1   0   0
    #2   5   6
    

    Then use negative indexing to remove the first (bogus) row

    a<-a[-1,]
    a
    
    #    one two
    #2   5   6
    

    Note: it messes up the index (far left). I haven't figured out how to prevent that (anyone else?), but most of the time it probably doesn't matter.

提交回复
热议问题