R name column when creating data frame

4.2k Views Asked by At

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
3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

When you create your data frame, don't have the double brackets:

newDigit1 <- data.frame(security_id = rsPred1$security_id)

Not

newDigit1 <- data.frame((security_id = rsPred1$security_id))
0
On

simply remove one bracket:

newDigit1 <- data.frame(security_id = rsPred1$security_id)

should be working now!