vaettchen
vaettchen

Reputation: 7659

colname does not show as expected

I have a data.frame y with 18 columns: the last one I added via

y$ced <- Limt

where Limt is a numerical vector of fitting length. Now this happens:

colnames( y )    
...
[13] "is_term"   "is_cover"  "is_other"  "CoRI"      "Prot"      "ced"
                                                                  ^^^

where the last colname is perfectly as expected. But:

head( y, 1 )
....
  is_price is_term is_cover is_other CoRI Prot Limt
1                                       0    0 5000
                                               ^^^^

Where, for me totally unexpectedly, the original variable name shows up as a header.

y$ced brings up the expected numbers, while

y$Limt
NULL

Probably this is how it should be but I did not find an explanation. I'd be very grateful for a hint where to look why this is how it is, and how to get the desired ced instead. Working around the issue is easy but I really want to know...

I tried colnames( y )[18] <- "ced" but this die not help.

sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: x86_64-pc-linux-gnu (64-bit)

Reproducible example - not sure whether this is good enough but the only thing that comes to my mind:

> x <- head( y$ced )
> x
   Limt
1  5000
2 10000
3 20000
4 40000
5  5000
6 10000
> dput( x )
structure(list(ced = structure(list(Limt = c(5000, 10000, 20000, 
40000, 5000, 10000)), .Names = "Limt", row.names = c(NA, 6L), class = "data.frame")), .Names = "ced", row.names = c(NA, 
6L), class = "data.frame")

I see the .Names thing there, that's probably it. I used RSQLite to get the data from a database file, is that how it turns up?

Upvotes: 2

Views: 1851

Answers (1)

flodel
flodel

Reputation: 89057

Most likely, you are not assigning a vector as you say, but a data.frame:

y <- head(cars, 3)
Limt <- data.frame(Limt = 1:3)
y$ced <- Limt
names(y)
# [1] "speed" "dist"  "ced"
y
#       speed dist Limt
# 1     4    2    1
# 2     4   10    2
# 3     7    4    3

str(y)
# 'data.frame': 3 obs. of  3 variables:
#  $ speed: num  4 4 7
#  $ dist : num  2 10 4
#  $ ced  :'data.frame':    3 obs. of  1 variable:
#   ..$ Limt: int  1 2 3

It will work as expected if you assign a vector:

y$ced <- Limt$Limt
y 
#   speed dist ced
# 1     4    2   1
# 2     4   10   2
# 3     7    4   3

Upvotes: 2

Related Questions