### data frame 1, variable 'y' with variable.label 'test participation'
df1 <- data.frame ( id = 1:3, sex = factor ( c("male", "male", "female")),
happy = c("low", "low", "medium"))
attr(df1[,"happy"], "variable.label") <- "happieness in the workplace"
### data frame 2 without labels
df2 <- data.frame ( id = as.factor(c(2,2,4)), status = factor ( c("married", "married", "single")),
convicted = c(FALSE, FALSE, TRUE))
### lost label after merging
df3 <- merge(df1, df2, all = TRUE)
attr(df3[,"happy"], "variable.label")
### maintain label
df4 <- mergeAttr(df1, df2, all = TRUE, onlyVarValLabs = FALSE)
attr(df4[,"happy"], "variable.label")
### adapt messages
df5 <- mergeAttr(df1, df2, all = TRUE, onlyVarValLabs = FALSE, unitName = "student",
xName = "student questionnaire", yName = "school questionnaire",
verbose = c("match", "unique"))
### In the following, the original examples of the `merge` function from the base
### package are called again using `mergeAttr` to illustrate the messages output in each case.
authors <- data.frame(
surname = c("Tukey", "Venables", "Tierney", "Ripley", "McNeil"),
nationality = c("US", "Australia", "US", "UK", "Australia"),
deceased = c("yes", rep("no", 4)))
authorN <- within(authors, { name <- surname; rm(surname) })
books <- data.frame(
name = c("Tukey", "Venables", "Tierney",
"Ripley", "Ripley", "McNeil", "R Core"),
title = c("Exploratory Data Analysis",
"Modern Applied Statistics ...",
"LISP-STAT",
"Spatial Statistics", "Stochastic Simulation",
"Interactive Data Analysis",
"An Introduction to R"),
other.author = c(NA, "Ripley", NA, NA, NA, NA,
"Venables & Smith"))
(m0 <- mergeAttr(authorN, books, setAttr=FALSE))
(m1 <- mergeAttr(authors, books, by.x = "surname", by.y = "name", setAttr=FALSE))
m2 <- mergeAttr(books, authors, by.x = "name", by.y = "surname", setAttr=FALSE)
stopifnot(exprs = {
all.equal(m0, m2[, names(m0)], check.attributes = FALSE)
as.character(m1[, 1]) == as.character(m2[, 1])
all.equal(m1[, -1], m2[, -1][ names(m1)[-1] ])
})
## "R core" is missing from authors and appears only here :
mergeAttr(authors, books, by.x = "surname", by.y = "name", all = TRUE, setAttr=FALSE)
## example of using 'incomparables'
x <- data.frame(k1 = c(NA,NA,3,4,5), k2 = c(1,NA,NA,4,5), data = 1:5)
y <- data.frame(k1 = c(NA,2,NA,4,5), k2 = c(NA,NA,3,4,5), data = 1:5)
mergeAttr(x, y, by = c("k1","k2"), setAttr=FALSE) # NA's match
mergeAttr(x, y, by = "k1", setAttr=FALSE) # NA's match, so 6 rows
Run the code above in your browser using DataLab