The function dplyr::pull()
pull a single column as a vector. This is useful if you need to pipe (|>
) a column as a vector into another function.
Tidyverse reference page
Dataset
For demonstration we’ll load the mammal_sleep_tbl
data from the mgrtibbles package (hyperlink includes install instructions).
#Load package
library("mgrtibbles")
#mammal_sleep_tbl tibble for demonstration
mgrtibbles::mammal_sleep_tbl
# A tibble: 62 × 11
species body_wt brain_wt non_dreaming dreaming total_sleep life_span
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Africanelephant 6.65e+3 5.71 NA NA 3.3 38.6
2 Africangiantpou… 1 e+0 0.0066 6.3 2 8.3 4.5
3 ArcticFox 3.38e+0 0.0445 NA NA 12.5 14
4 Arcticgroundsqu… 9.2 e-1 0.0057 NA NA 16.5 NA
5 Asianelephant 2.55e+3 4.60 2.1 1.8 3.9 69
6 Baboon 1.06e+1 0.180 9.1 0.7 9.8 27
7 Bigbrownbat 2.3 e-2 0.0003 15.8 3.9 19.7 19
8 Braziliantapir 1.6 e+2 0.169 5.2 1 6.2 30.4
9 Cat 3.3 e+0 0.0256 10.9 3.6 14.5 28
10 Chimpanzee 5.22e+1 0.44 8.3 1.4 9.7 50
# ℹ 52 more rows
# ℹ 4 more variables: gestation <dbl>, predation <fct>, exposure <fct>,
# danger <fct>
A single column to a vector
Pull the column “species” to a vector.
mammal_sleep_tbl |> dplyr::pull(species)
[1] "Africanelephant" "Africangiantpouchedrat"
[3] "ArcticFox" "Arcticgroundsquirrel"
[5] "Asianelephant" "Baboon"
[7] "Bigbrownbat" "Braziliantapir"
[9] "Cat" "Chimpanzee"
[11] "Chinchilla" "Cow"
[13] "Deserthedgehog" "Donkey"
[15] "EasternAmericanmole" "Echidna"
[17] "Europeanhedgehog" "Galago"
[19] "Genet" "Giantarmadillo"
[21] "Giraffe" "Goat"
[23] "Goldenhamster" "Gorilla"
[25] "Grayseal" "Graywolf"
[27] "Groundsquirrel" "Guineapig"
[29] "Horse" "Jaguar"
[31] "Kangaroo" "Lessershort-tailedshrew"
[33] "Littlebrownbat" "Man"
[35] "Molerat" "Mountainbeaver"
[37] "Mouse" "Muskshrew"
[39] "NAmericanopossum" "Nine-bandedarmadillo"
[41] "Okapi" "Owlmonkey"
[43] "Patasmonkey" "Phanlanger"
[45] "Pig" "Rabbit"
[47] "Raccoon" "Rat"
[49] "Redfox" "Rhesusmonkey"
[51] "Rockhyrax(Heterob)" "Rockhyrax(Procaviahab)"
[53] "Roedeer" "Sheep"
[55] "Slowloris" "Starnosedmole"
[57] "Tenrec" "Treehyrax"
[59] "Treeshrew" "Vervet"
[61] "Wateropossum" "Yellow-belliedmarmot"
Pull the column “total_sleep” to a vector and calculate the mean value.
Note: Requires dplyr::filter(!is.na(total_sleep))
as if any NAs are passed to mean()
the result will be NA.
mammal_sleep_tbl |> dplyr::filter(!is.na(total_sleep)) |> dplyr::pull(total_sleep) |> mean()