with by which

knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(message = FALSE)
library(tidyverse)

with()

  • with(dataset, expression)
  • with() applies an expression to a dataset
data1 <- iris[,4:5] %>% filter(Species != "setosa")
with(data1, t.test(Petal.Width ~ Species))

# or you have to create 2 vectors
versi <- data1 %>% filter(Species == "versicolor") %>% select(-Species)
verg <- data1 %>% filter(Species == "virginica") %>% select(-Species)
t.test(versi, verg)

# actually t.test() has formula interface...
t.test(Petal.Width ~ Species, data = data1)
# without with(), we would be stuck here:
z = mean(mtcars$cyl + mtcars$disp + mtcars$wt); z

# using with(), we can clean this up:
z = with(mtcars, mean(cyl + disp + wt)); z
  • tidyverse functions all have “data” argument, so with() is not needed as much
  • do not use attach(), if you update colnames, sometimes old colnames attached to GlobalEnv might not sync

by()

  • by(data, factorlist, function)
  • by() applies a function to each level of a factor(s)
iris[,5] %>% class()
by(iris, iris$Species, function(x) mean(x$Petal.Length))
by(iris, iris$Species, function(x) mean(x$Petal.Length * 10 + 2))

which()

  • find index of TRUE in vector
which(letters == "g")
which(letters[1:5] != "b")
which(letters[1:5] != "b" & letters[1:5] != "a")

EOF

Previous
Next