Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (5.3k points)

Is there a more succinct way to get one column of a dplyr tbl as a vector, from a tbl with database back-end (i.e. the data frame/table can't be subset directly)?

require(dplyr)

db <- src_sqlite(tempfile(), create = TRUE)

iris2 <- copy_to(db, iris)

iris2$Species

# NULL

That would have been too easy, so

collect(select(iris2, Species))[, 1]

# [1] "setosa"     "setosa"     "setosa"     "setosa"  etc.

But it seems a bit clumsy.

1 Answer

0 votes
by

To extract a column as a vector, you can use the pull function from the dplyr package.

The basic syntax is given below:

pull(.data, var =)

.data:- A table of data

 

var :-A variable specified as:

 
  • A literal variable name

 
  • A positive integer, giving the position counting from the left

 
  • A negative integer, giving the position counting from the right.

 

In your case:

library("dplyr")

db <- src_sqlite(tempfile(), create = TRUE)

iris2 <- copy_to(db, iris)

vec <- pull(iris2, Species)

head(vec)

Output:

[1] "setosa" "setosa" "setosa" "setosa" "setosa" "setosa"

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...