Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help to make function(\"dummify()\") in R. The instruction for dummify fu

ID: 3878911 • Letter: I

Question

I need help to make function("dummify()") in R. The instruction for dummify function is stated below.

Q . Write a function dummify() that takes a factor or a character vector, and which returns a matrix with dummy indicators. Assuming that the factor has k categories (i.e. k levels), include an argument all that lets you specify whether to return k binary indicators, or k 1 indicators. You should be able to call dummify() like this:

cyl <- factor(mtcars$cyl)

dummify() <- # all categories

CYL1 <- dummify(cyl,all=TRUE)

#minus one category

CYL2 <- dummify(cyl,all=FALSE)

Explanation / Answer


dummify <- function(x, all = FALSE) {
if (!is.factor(x)) x <- as.factor(x)
categories <- levels(x)
num_categories <- length(categories)
if (!all) {
    num_categories <- length(categories) - 1
}
dummies <- matrix(0, nrow = length(x), ncol = num_categories)
for (k in 1:num_categories) {
    dummies[x == categories[k],k] <- 1
}
colnames(dummies) <- categories[1:num_categories]
dummies
}

# test it
cyl <- factor(mtcars$cyl)
CYL1 <- dummify(cyl, all = TRUE)
CYL2 <- dummify(cyl, all = FALSE)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote