Mutate: Compute new column(s)
library(dplyr)
msleep <- read.csv("./data/msleep_ggplot2.csv")
msleep %>%
mutate(sleep_new=sleep_total + sleep_rem) %>%
head()
## name genus vore order conservation ## 1 Cheetah Acinonyx carni Carnivora lc ## 2 Owl monkey Aotus omni Primates <NA> ## 3 Mountain beaver Aplodontia herbi Rodentia nt ## 4 Greater short-tailed shrew Blarina omni Soricomorpha lc ## 5 Cow Bos herbi Artiodactyla domesticated ## 6 Three-toed sloth Bradypus herbi Pilosa <NA> ## sleep_total sleep_rem sleep_cycle awake brainwt bodywt sleep_new ## 1 12.1 NA NA 11.9 NA 50.000 NA ## 2 17.0 1.8 NA 7.0 0.01550 0.480 18.8 ## 3 14.4 2.4 NA 9.6 NA 1.350 16.8 ## 4 14.9 2.3 0.1333333 9.1 0.00029 0.019 17.2 ## 5 4.0 0.7 0.6666667 20.0 0.42300 600.000 4.7 ## 6 14.4 2.2 0.7666667 9.6 NA 3.850 16.6
Transmute: Compute new column(s), drop others.
head(transmute(msleep,sleep_new=sleep_rem+sleep_total))
## sleep_new ## 1 NA ## 2 18.8 ## 3 16.8 ## 4 17.2 ## 5 4.7 ## 6 16.6
Mutate_if: Apply funs to all columns of one type. Reemplaza los datos antiguos con los nuevos.
msleep %>% mutate_if(is.numeric, log2)%>% head()
## name genus vore order conservation ## 1 Cheetah Acinonyx carni Carnivora lc ## 2 Owl monkey Aotus omni Primates <NA> ## 3 Mountain beaver Aplodontia herbi Rodentia nt ## 4 Greater short-tailed shrew Blarina omni Soricomorpha lc ## 5 Cow Bos herbi Artiodactyla domesticated ## 6 Three-toed sloth Bradypus herbi Pilosa <NA> ## sleep_total sleep_rem sleep_cycle awake brainwt bodywt ## 1 3.596935 NA NA 3.572890 NA 5.6438562 ## 2 4.087463 0.8479969 NA 2.807355 -6.011588 -1.0588937 ## 3 3.847997 1.2630344 NA 3.263034 NA 0.4329594 ## 4 3.897240 1.2016339 -2.9068906 3.185867 -11.751659 -5.7178568 ## 5 2.000000 -0.5145732 -0.5849625 4.321928 -1.241270 9.2288187 ## 6 3.847997 1.1375035 -0.3833286 3.263034 NA 1.9448584
Mutate_all: Apply funs to every column.
msleep %>% select(sleep_total, sleep_rem) %>% mutate_all(funs(log(.),log2(.))) %>% names()
## [1] "sleep_total" "sleep_rem" "sleep_total_log" ## [4] "sleep_rem_log" "sleep_total_log2" "sleep_rem_log2"
Mutate_at: Apply funs to specific columns.
msleep %>% mutate_at(vars(sleep_total),funs(log(.),log2(.))) %>% names()
## [1] "name" "genus" "vore" "order" ## [5] "conservation" "sleep_total" "sleep_rem" "sleep_cycle" ## [9] "awake" "brainwt" "bodywt" "log" ## [13] "log2"


