【发布时间】:2016-02-13 09:44:58
【问题描述】:
来自本网站上类似问题的其他答案,例如从像 http://www.r-tutor.com/r-introduction/data-frame/data-frame-column-vector 这样的页面中,我似乎从 data.frame、data[ , "col"] 和 data$col 中提取变量应该产生相同的结果。但现在我在 Excel 中有一些数据:
LU Urban_LU LU_Index Urban_LU_index
Residential Residential 2 0
Rural residential Residential 3 0
Commercial Commercial 4 1
Public institutions including education Industrial 5 1
Industry Industrial 7 2
)
我用read_excel 阅读它来自readxl 包:
library(readxl)
data <- read_excel("data.xlsx", "Sheet 1")
现在我从数据框中提取一个变量,使用[ 或$:
data[ , "LU"]
# Source: local data frame [5 x 1]
#
# LU
# (chr)
# 1 Residential
# 2 Rural residential
# 3 Commercial
# 4 Public institutions including education
# 5 Industry
data$LU
# [1] "Residential" "Rural residential"
# [3] "Commercial" "Public institutions including education"
# [5] "Industry"
length(data[ , "LU"])
# [1] 1
length(data$LU)
# [1] 5
另外,我发现可疑的是从read_excel 获得的数据的类别以及来自两种不同提取模式的数据:
class(data)
# [1] "tbl_df" "tbl" "data.frame"
class(data[ , "LU"])
# [1] "tbl_df" "data.frame"
class(data$LU)
# [1] "character"
>
那么[ , "col"] 和$col 有什么区别?我是否遗漏了手册中的某些内容,或者这是一个特殊情况?另外,tbl_df 和 tbl 类标识符是什么?我怀疑它们是我困惑的原因,它们是什么意思?
【问题讨论】:
-
是的,这是一个特例。你进入了哈德利的世界。如果你做
data <- as.data.frame(data),你在做data[, "LU"]时应该很好。由于使用了readxl,您需要这样做。 -
data不是“真正的”data.frame。 -
正确 - 确实如此。为简洁起见,我忽略了最初的问题,即我已经发现 readxl 文档没有明确记录返回类型是可疑的。那么有没有什么地方可以让我了解那里发生了什么?