【问题标题】:Extract a single value from a dataframe/tibble the tidy/dplyr way?以 tidy/dplyr 的方式从数据框/tibble 中提取单个值?
【发布时间】:2021-12-30 14:49:16
【问题描述】:

我知道几种从数据框/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"] 

从数据框/tibble 中提取单个特定值的速记/更优雅/单行 tidyverse 方法是什么?

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    这里有一些可能性:

    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"
    

    这里是基本的 R 代码

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

    【讨论】:

    • 谢谢!你的回答让我也想到了这个 start_date %>% deframe() %>% pluck("Alexander")
    猜你喜欢
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2017-10-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多