是否有更简洁的方法来获得一个dplyr tbl的一列作为一个向量,从一个tbl与数据库后端(即数据帧/表不能直接子集)?
require(dplyr)
db <- src_sqlite(tempfile(), create = TRUE)
iris2 <- copy_to(db, iris)
iris2$Species
# NULL
那太简单了,所以
collect(select(iris2, Species))[, 1]
# [1] "setosa" "setosa" "setosa" "setosa" etc.
但是看起来有点笨拙。
另一种将列提取为向量的更快方法是
使用c()函数将数据帧转换为列表,然后:
c(iris)$Species
c(iris)$Sepal.Length
使用dplyr方法从列到向量:
iris %>% select(Sepal.Length) %>%
as.matrix() %>%
as.vector()
如果你想要数据集的所有值
作为一个向量,你只需做:
# I have this tibble:
iris %>% as_tibble() %>% head(3)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
按列值顺序(5.1,4.9,4.7,…)执行以下操作:
iris %>% as_tibble() %>% as.matrix %>% as.vector()
[1] "5.1" "4.9" "4.7"
[4] "4.6" "5.0" "5.4"
[7] "4.6" "5.0" "4.4"
[10] "4.9" "5.4" "4.8"
....
[742] "virginica" "virginica" "virginica"
[745] "virginica" "virginica" "virginica"
[748] "virginica" "virginica" "virginica"
对行值顺序(5.1,3.5,1.4,…)执行以下操作:
iris %>% as_tibble() %>% as.matrix %>% t() %>% as.vector()
[1] "5.1" "3.5" "1.4"
[4] "0.2" "setosa" "4.9"
[7] "3.0" "1.4" "0.2"
[10] "setosa" "4.7" "3.2"
[13] "1.3" "0.2" "setosa"
....
[739] "2.0" "virginica" "6.2"
[742] "3.4" "5.4" "2.3"
[745] "virginica" "5.9" "3.0"
[748] "5.1" "1.8" "virginica"