【问题标题】:Difference between data[ , "col"] and data$coldata[ , "col"] 和 data$col 之间的区别
【发布时间】:2016-02-13 09:44:58
【问题描述】:

来自本网站上类似问题的其他答案,例如从像 http://www.r-tutor.com/r-introduction/data-frame/data-frame-column-vector 这样的页面中,我似乎从 data.framedata[ , "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_dftbl 类标识符是什么?我怀疑它们是我困惑的原因,它们是什么意思?

【问题讨论】:

  • 是的,这是一个特例。你进入了哈德利的世界。如果你做data &lt;- as.data.frame(data),你在做data[, "LU"]时应该很好。由于使用了readxl,您需要这样做。
  • data 不是“真正的”data.frame。
  • 正确 - 确实如此。为简洁起见,我忽略了最初的问题,即我已经发现 readxl 文档没有明确记录返回类型是可疑的。那么有没有什么地方可以让我了解那里发生了什么?

标签: r dataframe


【解决方案1】:

更多扩展评论:

readxl::read_xl 返回类tbl_df 的输出这一事实似乎在?read_xl 中记录得很差。尽管announcement of readxl on the RStudio blog 中提到了这种行为:

"[read_xlr]返回类c("tbl_df", "tbl", "data.frame")的输出"

要了解有关tbl_df 的更多信息,我们需要查阅dplyr 帮助页面。在?dplyr::tbl_dfMethods 部分,我们发现 “tbl_df 实现了两个重要的基本方法:[ 从不简化(丢弃),所以总是返回 data.frame”。

有关更多背景信息,请阅读 ?[.data.frame 中的 drop 参数。

相关问答:Extract a dplyr tbl column as a vectorBest practice to get a dropped column in dplyr tbl_df

另请参阅the 'original' issue on github 和其中的讨论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    相关资源
    最近更新 更多