Here is a data.table contains four pets’ name, species and weight:
library(data.table)
pets = data.table(name = c("Senor", "Cookie", "Lucky", "Meow Meow"),
species = c("dog", "dog", "bird", "cat"),
weight = c(26, 13, 0.5, 6))
Please:
pet_weight = pets[, .(name, weight)]
pet_weight
## name weight
## 1: Senor 26.0
## 2: Cookie 13.0
## 3: Lucky 0.5
## 4: Meow Meow 6.0
senor_weight = pets[name == "Senor", "weight"]
senor_weight
## [1] "weight"
dogs_weight = pets[species == "dog", .(name, weight)]
dogs_weight
## name weight
## 1: Senor 26
## 2: Cookie 13
pets[name == "Cookie", weight := 15]
pets
## name species weight
## 1: Senor dog 26.0
## 2: Cookie dog 15.0
## 3: Lucky bird 0.5
## 4: Meow Meow cat 6.0
pet_stat = pets[, .(avg_weight = mean(weight), count = .N), by = "species"]
pet_stat
## species avg_weight count
## 1: dog 20.5 2
## 2: bird 0.5 1
## 3: cat 6.0 1