Search code examples
rdataframedplyrindexingnumeric

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

  • Somewhat strangely, when we create a similar data.frame manually, we can retrieve the value as a vector with .[1,1]
> data.frame(n=1) -> b
> b[1,1]
[1] 1

Solution

  • 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