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

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

    One way to make this work generically and with the least amount of re-typing the column names is the following. This method doesn't require hacking the NA or 0.

    rs <- data.frame(i=numeric(), square=numeric(), cube=numeric())
    for (i in 1:4) {
        calc <- c(i, i^2, i^3)
        # append calc to rs
        names(calc) <- names(rs)
        rs <- rbind(rs, as.list(calc))
    }
    

    rs will have the correct names

    > rs
        i square cube
    1   1      1    1
    2   2      4    8
    3   3      9   27
    4   4     16   64
    > 
    

    Another way to do this more cleanly is to use data.table:

    > df <- data.frame(a=numeric(0), b=numeric(0))
    > rbind(df, list(1,2)) # column names are messed up
    >   X1 X2
    > 1  1  2
    
    > df <- data.table(a=numeric(0), b=numeric(0))
    > rbind(df, list(1,2)) # column names are preserved
       a b
    1: 1 2
    

    Notice that a data.table is also a data.frame.

    > class(df)
    "data.table" "data.frame"
    

提交回复
热议问题