Home > Blockchain >  Extract a single value from a dataframe/tibble the tidy/dplyr way?
Extract a single value from a dataframe/tibble the tidy/dplyr way?

Time:12-31

I know a few ways to get a single value out of a dataframe/tibble.

library(dplyr)

start_date <- tibble::tribble(
  ~StaffAbbrev, ~starting_date,
  "Alexander", "2021-08-23",
  "Cornelis", "2021-08-23",
  "Sotirchos", "2021-08-23",
  "Zhao", "2021-08-23",
  "Park", "2022-02-14",
  "Sarkar", "2022-04-04"
)

#Tidyverse way
Alexander_start_v1 <- start_date %>%
  filter(StaffAbbrev == "Alexander") %>%
  select(starting_date) %>%
  unlist() %>%
  unname() 

#Base R way
Alexander_start_v2=start_date$starting_date[start_date$StaffAbbrev=="Alexander"] 

Is shorthand/more elegant/one-liner tidyverse way to extract a single specific value out of a dataframe/tibble?

CodePudding user response:

Here are some possibilities:

library(dplyr)
library(tibble)
start_date %>% deframe %>% getElement("Alexander")
## [1] "2021-08-23"

library(dplyr)
library(tibble)
start_date %>% deframe %>% .[["Alexander"]]
## [1] "2021-08-23"

library(dplyr)
start_date %>% filter(StaffAbbrev == "Alexander") %>% pull
## [1] "2021-08-23"

library(dplyr)
library(magrittr)
start_date %>% filter(StaffAbbrev == "Alexander") %$% starting_date
## [1] "2021-08-23"

and here is base R code

with(start_date, starting_date[match("Alexander", StaffAbbrev)])
## [1] "2021-08-23"
  • Related