【问题标题】:as.vector() fails on data.table object [duplicate]as.vector() 在 data.table 对象上失败 [重复]
【发布时间】:2018-07-09 12:27:50
【问题描述】:

我需要以向量的形式从 data.table 中提取一列。我知道$ 有效,[] 无效。然而,as.vector() 在单个维度的 data.table 对象上失败了

    library(data.table)
    dt <- iris
    setDT(dt)
    oneCol1 <- dt$Sepal.Length[1:100] # produces a vector of 100 elements, fine
    oneCol2 <- dt[1:100,1] # produces a DT 100 rows by 1 column. I understand limitation.
    v <- as.vector(oneCol2) 
    is.vector(v) # FALSE

文档说as.vector()“试图强制... x,一个 R 对象。”不过,什么也没发生。 v 仍然是一个 DT 对象。

当然,我可以使用第一种方法,但我想知道为什么as.vector() 不起作用。

【问题讨论】:

  • 您基本上是在告诉 R 将数据表/数据框转换为向量。这应该如何工作,只是做v &lt;- as.vector(oneCol2$Sepal.Length)有什么问题?
  • 你需要unlist
  • "我需要提取一列" -- dt[[1]][1:100]?您也可以输入vignette("datatable-faq") 并阅读第一个答案。 (我建议阅读全文。)

标签: r vector data.table


【解决方案1】:

数据框是列表。即使您选择了一行数据,它仍然被视为一个列表。

使用 unlist 代替:

 library(data.table)
dt <- iris
setDT(dt)
oneCol1 <- dt$Sepal.Length[1:100] # produces a vector of 100 elements, fine
oneCol2 <- dt[1:100,1] # produces a DT 100 rows by 1 column. I understand limitation.
t<-unlist(oneCol2)
is.vector(t) # true

【讨论】:

    猜你喜欢
    • 2014-06-24
    • 1970-01-01
    • 2011-07-16
    • 2020-08-04
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2019-07-24
    相关资源
    最近更新 更多