Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr::select one column and output as vector [duplicate]

dplyr::select results in a data.frame, is there a way to make it return a vector if the result is one column?

Currently, I have to do extra step (res <- res$y) to convert it to vector from data.frame, see this example:

#dummy data df <- data.frame(x = 1:10, y = LETTERS[1:10], stringsAsFactors = FALSE)  #dplyr filter and select results in data.frame res <- df %>% filter(x > 5) %>% select(y) class(res) #[1] "data.frame"  #desired result is a character vector res <- res$y class(res) #[1] "character" 

Something as below:

res <- df %>% filter(x > 5) %>% select(y) %>% as.character res # This gives strange output [1] "c(\"F\", \"G\", \"H\", \"I\", \"J\")"  # I need: # [1] "F" "G" "H" "I" "J" 
like image 819
zx8754 Avatar asked Nov 26 '14 12:11

zx8754


People also ask

How do I select a specific column in R studio?

To pick out single or multiple columns use the select() function. The select() function expects a dataframe as it's first input ('argument', in R language), followed by the names of the columns you want to extract with a comma between each name.

How do I convert a Dataframe to a vector in R?

For the Conversion of dataframe into a vector, we can simply pass the dataframe column name as [[index]]. Approach: We are taking a column in the dataframe and passing it into another variable by the selection method. Selection method can be defined as choosing a column from a data frame using ” [[]]”.


2 Answers

The best way to do it (IMO):

library(dplyr) df <- data_frame(x = 1:10, y = LETTERS[1:10])  df %>%    filter(x > 5) %>%    .$y 

In dplyr 0.7.0, you can now use pull():

df %>% filter(x > 5) %>% pull(y) 
like image 104
hadley Avatar answered Oct 13 '22 08:10

hadley


Something like this?

> res <- df %>% filter(x>5) %>% select(y) %>% sapply(as.character) %>% as.vector > res [1] "F" "G" "H" "I" "J" > class(res) [1] "character" 
like image 26
LyzandeR Avatar answered Oct 13 '22 09:10

LyzandeR