What's the most idiomatic way to extract a single element from a tibble?

Hi all,

I would like to return the last value of a given column from a tibble. What's the most tidyverse-y way of doing it? It looks like I need purrr:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(purrr)

test <- structure(list(iso3c = c("GBR", "GBR", "GBR", "GBR", "GBR", "GBR", 
                                 "GBR", "GBR", "GBR", "GBR"), country = c("United Kingdom", "United Kingdom", 
                                                                          "United Kingdom", "United Kingdom", "United Kingdom", "United Kingdom", 
                                                                          "United Kingdom", "United Kingdom", "United Kingdom", "United Kingdom"
                                 ), date = structure(c(18293, 18294, 18295, 18296, 18297, 18298, 
                                                       18299, 18300, 18301, 18302), class = "Date"), new_cases = c(NA, 
                                                                                                                   0, 0, 0, 0, 0, 1, 0, 0, 5), ave_new_cases = c(NA, NA, NA, NA, 
                                                                                                                                                                 NA, NA, NA, 0.142857142857143, 0.142857142857143, 0.857142857142857
                                                                                                                   ), new_deaths = c(NA, 0, 0, 0, 0, 0, 0, 0, 0, 0), ave_new_deaths = c(NA, 
                                                                                                                                                                                        NA, NA, NA, NA, NA, NA, 0, 0, 0)), row.names = c(NA, -10L), class = c("tbl_df", 
                                                                                                                                                                                                                                                              "tbl", "data.frame"))
p <- test %>% 
  select(ave_new_cases) %>%
  slice_tail() %>%
  pluck(1,1)

print(p)
#> [1] 0.8571429

Created on 2020-06-04 by the reprex package (v0.3.0)

It can be done without purrr by using pull(). How's this?

test %>% 
  select(ave_new_cases) %>% 
  slice_tail() %>% 
  pull()

You could reduce the code by one line if you did:

test %>% 
  slice_tail() %>% 
  pull(ave_new_cases)
3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.