Reputation: 52328
I am trying to extract the value from a 1 x 1 data.frame produced with dplyr as a vector
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
.[1,1]
> data.frame(n=1) -> b
> b[1,1]
[1] 1
Upvotes: 1
Views: 4149
Reputation: 51
Old post, but adding a dplyr solution.
df_num <- iris %>%
summarise(ifelse(tally(.) == 150, 1, 0)) %>%
unlist() %>%
as.numeric()
Upvotes: 2
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
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