colname未按预期显示

时间:2012-12-12 10:48:41

标签: r

我有一个包含18列的data.frame y:我通过

添加的最后一列
y$ced <- Limt

其中Limt是拟合长度的数值向量。现在发生这种情况:

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

最后一个colname完全符合预期。但是:

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

对于我来说,完全出乎意料的是,原始变量名称显示为标题。

y$ced会显示预期的数字,而

y$Limt
NULL

可能这应该是这样,但我没有找到解释。我非常感谢提示在哪里查看原因是什么,以及如何获得所需的ced。解决这个问题很容易,但我真的想知道......

我试过colnames( y )[18] <- "ced",但这没有用。

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

可重复的例子 - 不确定这是否足够好但是我想到的唯一的事情是:

> 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")

我在那里看到.Names的东西,可能就是这样。我使用RSQLite从数据库文件中获取数据,它是如何出现的?

1 个答案:

答案 0 :(得分:2)

很有可能,你没有像你说的那样分配一个矢量,而是一个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

如果您指定了一个矢量,它将按预期工作:

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