stevec
stevec

Reputation: 52328

Extract the single value from a 1 x 1 data.frame produced with dplyr as a vector?

I am trying to extract the value from a 1 x 1 data.frame produced with dplyr as a vector

Example

Suppose we have

library(dplyr)

df <- iris %>% summarise(ifelse(tally(.) == 150, 1, 0))

df
#   n
# 1 1

I expected df[1,1] to return the desired result [1] 1 (i.e. a vector), but, instead it returns a matrix.

> df[1,1]
     n
[1,] 1

Notes

> data.frame(n=1) -> b
> b[1,1]
[1] 1

Upvotes: 1

Views: 4149

Answers (4)

ThomasIsCoding
ThomasIsCoding

Reputation: 101753

A simple c + t combo can manage it

> c(t(df))
[1] 1

Upvotes: 1

Federico Dallo
Federico Dallo

Reputation: 51

Old post, but adding a dplyr solution.

df_num <- iris %>% 
  summarise(ifelse(tally(.) == 150, 1, 0)) %>% 
  unlist() %>% 
  as.numeric()

Upvotes: 2

stevec
stevec

Reputation: 52328

In addition to @sachin's answer, two additional methods may also work

df %>% as.numeric
[1] 1

and

df %>% unlist %>% unname
[1] 1

Upvotes: 3

sachin2014
sachin2014

Reputation: 462

You can get the vector using df[[1,1]]

Output

> df[[1,1]]
[1] 1

Here is a simple example that explains how it works using test data

df1 <- data.frame(a = c(1,2,3), b = c(4,5,6))

Output

> df1['a']
  a
1 1
2 2
3 3
> df1[['a']]
[1] 1 2 3

Upvotes: 2

Related Questions