I have a multi-part question I've been trying to figure on building on some of my functions I've been able to cobble together.
Here's my dataframe:
dat1 <- data.frame(
stringsAsFactors = FALSE,
var1 = c("know", "see", "know", "hear", "hear", "see", "see", "know"),
var2 = c(1, 2, 3, 4, 5, 6, 7, 8),
var3 = c(1, 1, 2, 2, 3, 3, 4, 4),
subCat1 = c("0", "0", "0", "0", "0", "0", "0", "0"))
Here are the inputs I want to use in my functions:
myID <- c(1, 2, 4)
myCat= c("remembering", "learning", "forgetting")
Part One
I was able to get myFunA function to work:
myFunA <- function (df, x, y) {
df %>%
mutate(subCat1 = ifelse(var2 %in% x, y, subCat1))
}
dat2 <- dat1 %>%
myFun2 (myID,myCat)
I'm not exactly sure why it works, because this function doesn't include the argument for "False", but it does work.
But when I try to have the user input the colName for subCat1 ("z" in the function below) I get errors with everything I try that include variations of the following:
myFunB <- function (df, x, y, z) {
df %>%
mutate(z = ifelse(var2 %in% x, y, z)
}
datA <- dat1 %>%
myFunB(myID, myCat, subCat1)
I get a result, but not what I want. This is what I'm expecting. The result I want is "dat2".
I don't understand why when z is added to the function, ifelse no longer works.
I don't know how to add "do nothing"Z to the function.
And when I try to change the function to if without else, I get another error.
myFunB <- function (df, x, y, z) {
df %>%
mutate(z = if (var2 %in% x, y))
}
Part 2
I've also tried figuring out how to write variations of this function for multi conditions
myFunMulti <- function (df, x, y, z) {
df %>%
mutate(subCat1 = ifelse(var2 %in% x, && var3 %in% z), y, subCat1)
}
This is the result I'm expecting:
MultiExpected <- data.frame(
stringsAsFactors = FALSE,
var1 = c("know", "see", "know", "hear", "hear", "see", "see", "know"),
var2 = c(1, 2, 3, 4, 5, 6, 7, 8),
var3 = c(1, 1, 2, 2, 3, 3, 4, 4),
subCat1 = c("remembering", "0", "learning", "0", "0", "0", "0", "forgetting"))
Thank you.