Challenge10_MarcelaRobincon

Author

Marcela Robinson

Published

February 5, 2023

library(tidyverse)
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0     ✔ purrr   1.0.1
✔ tibble  3.1.8     ✔ dplyr   1.1.0
✔ tidyr   1.3.0     ✔ stringr 1.5.0
✔ readr   2.1.3     ✔ forcats 1.0.0
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
library(here)
here() starts at /home/runner/work/601_Winter_2022-2023/601_Winter_2022-2023
animal_weight<- here("posts", "_data", "animal_weight.csv")%>%
  read_csv()
Rows: 9 Columns: 17
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (1): IPCC Area
dbl (16): Cattle - dairy, Cattle - non-dairy, Buffaloes, Swine - market, Swi...

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
weights_stats<-function(animal_weight, pivot=F){
  dat <- tibble(
    id=ifelse(is.null(names(animal_weight)),NA,names(animal_weight)),
    st_mean = mean(animal_weight, na.rm = TRUE),
    st_median = median(animal_weight, na.rm = TRUE),
    st_sd = sd(animal_weight, na.rm = TRUE),
    st_min = min(animal_weight, na.rm = TRUE),
    st_max = max(animal_weight, na.rm = TRUE),
     )
  if(pivot){
    dat <- dat %>%
      pivot_longer(cols=-id)
  }
  return(dat)
}

n <- 100
a <- rnorm(n)
names(a) <- "a"
b <- runif(n)
names(b) <- "b"
c <- rgamma(n,1,1)
names(c) <- "c"

map_dfr(list(a,b,c),weights_stats,pivot=F)
# A tibble: 3 × 6
  id    st_mean st_median st_sd   st_min st_max
  <chr>   <dbl>     <dbl> <dbl>    <dbl>  <dbl>
1 a      0.0312  -0.00141 0.978 -2.71     2.43 
2 b      0.471    0.461   0.271  0.00192  0.987
3 c      0.995    0.671   0.906  0.0192   4.12 
map_dfr(list(a,b,c),weights_stats,pivot=T)
# A tibble: 15 × 3
   id    name         value
   <chr> <chr>        <dbl>
 1 a     st_mean    0.0312 
 2 a     st_median -0.00141
 3 a     st_sd      0.978  
 4 a     st_min    -2.71   
 5 a     st_max     2.43   
 6 b     st_mean    0.471  
 7 b     st_median  0.461  
 8 b     st_sd      0.271  
 9 b     st_min     0.00192
10 b     st_max     0.987  
11 c     st_mean    0.995  
12 c     st_median  0.671  
13 c     st_sd      0.906  
14 c     st_min     0.0192 
15 c     st_max     4.12   
# sanity check
weights_stats(animal_weight$Buffaloes)
# A tibble: 1 × 6
  id    st_mean st_median st_sd st_min st_max
  <lgl>   <dbl>     <dbl> <dbl>  <dbl>  <dbl>
1 NA       371.       380  28.3    295    380