Oh, yes, you're right. That was a typo on my part, So here's what I ran, but it still doesn't work.
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"))
myFunB <- function (df, x, y, z) {
z2 <- as.character(ensym(z))
df %>%
mutate(z = ifelse(var2 %in% x, y, z2))
}
myID <- c(1, 2, 4)
myCat <- c("remembering", "learning", "forgetting")
dat2 <- dat1 %>%
myFunB(myID, myCat, subCat1)
result <- data.frame(
stringsAsFactors = FALSE,
var1 = c("know","see","know","hear",
"hear","see","see","know"),
var2 = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L),
var3 = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L),
subCat1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L),
z = c("remembering","learning",
"subCat1","remembering","subCat1","subCat1","subCat1",
"subCat")
)
This almost does what I want, but instead of the data being entered into the "subCat1" column it's being entered into a new column named "z" and subCat1 is being entered as the "no" part of the ifelse statement.
The ifelse statement works for the following function, when "z" is hard coded into the function.
I want to the user to be able to enter the column name (and not have it hardcoded. This function still hard codes the name of the column into the function as "z", and it's overwriting all of the "no". I don't want any of the existing data to be overwritten (as in myFunA) but I want to be able the user to enter the column name, so I can get this result:
expected <- data.frame(
stringsAsFactors = FALSE,
var1 = c("know","see","know","hear",
"hear","see","see","know"),
var2 = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L),
var3 = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L),
subCat1 = c("remembering","learning","0",
"remembering","0","0","0","0")
)
I'm trying to wrap my brain around why the ifelse statement works with myFunA, but then behaves differently in myFunB.