Search code examples
rdataframecreation

R name column when creating data frame


I'm taking the columns from a data frame and using them to create another data frame, but the names keep getting jumbled instead of keeping the original name. How do I avoid this?

> newDigit1 <- data.frame((security_id = rsPred1$security_id))
> head(newDigit1)
  X.security_id...rsPred1.security_id.
1                                    1
2                                    6
3                                    5
4                                    3
5                                    3
6                                    2

It should be like this:

> newDigit1 <- data.frame((security_id = rsPred1$security_id))
> head(newDigit1)
                                security_id
1                                    1
2                                    6
3                                    5
4                                    3
5                                    3
6                                    2

Solution

  • It's because you've doubled up the brackets ((. Compare

    dfr <- data.frame(x = 1:5)
    #Case 1
    data.frame(x = dfr$x)
    #Case 2
    data.frame((x = dfr$x))
    

    In case 1, x = dfr$x is a name-value pair being passed into the data.frame function.

    In case 2, (x = dfr$x) returns a vector with no name, so R invents a temporary one and then passes that vector into the data.frame function.