Most concise way to get a value from within a tibble

﹥>﹥吖頭↗ 提交于 2021-02-11 05:56:40

问题


I'm setting up tests. I operate on test-data, then want to assure that the right value showed up in a cell in a tibble. I think there's a more concise way to this. Using the example band_instruments

library(tidyverse)
test_that("Musicians play instruments", {
      expect_equal(band_instruments %>% filter(name == "Paul") %>% pull("plays"),
                   "bass")
      expect_equal({band_instruments %>% filter(name == "Keith")}$plays,
                   "guitar")
})

This works, but it's too long, too wordy. What's the most concise, yet readable way to do such tests?


回答1:


This looks quite neat to me:

test_that("Musicians play instruments", {
  expect_equal(with(band_instruments, plays[name == "Paul"]), "bass")
  expect_equal(with(band_instruments, plays[name == "Keith"]), "guitar")})

Or perhaps this:

with(band_instruments, test_that("Musicians play instruments", {
  expect_equal(plays[name == "Paul"], "bass")
  expect_equal(plays[name == "Keith"], "guitar")}))


来源:https://stackoverflow.com/questions/61702740/most-concise-way-to-get-a-value-from-within-a-tibble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!