A simple example

The following example shows one use-case. Using Anderson's iris data, we calculate the regression of Petal.Length on Sepal.Length for each Species and then merge this slope coefficient back into the original data.

coefs  <- lapply(split(iris, iris$Species),
                 function(dat) lm(Petal.Length~Sepal.Length, dat)$coef)
coefs <- do.call("rbind",coefs)
coefs <- as.data.frame(coefs)
coefs$Species <- rownames(coefs)
coefs

library(lookup)
iris = transform(iris,
                 slope1 = lookup(iris$Species, coefs$Species, coefs[,"Sepal.Length"]),
                 slope2 = vlookup(iris$Species, coefs, "Species", "Sepal.Length"))
head(iris)

Admittedly, a better way to approach this problem would be with the dplyr package and the group_by and summarize functions. But, this example does not depend on external packages.

History

I wrote the lookup() function for my own personal in 2004 for the simple reason that I could never remember the syntax of the merge() function. When Jenny Bryan posted vlookup() on Twitter, I modified her version and decided there would be value in making both of these functions widely available in a package.



kwstat/lookup documentation built on July 17, 2024, 1:19 p.m.