I need some help converting a simple script to a function.
Here's my dataframe:
dat <- data.frame(
cat1 = c(4, 0, 1, 0, 4, 4),
cat2 = c(0, 4, 3, 2, 0, 0),
cat3 = c(0, 0, 0, 2, 0, 0)
)
I want to create new columns that tell me how many coders agreed across all of the the categories (cat1, cat2, cat3).
I use mutate to create the column "agree4" to indicate if all 4 coders agreed on the content that corresponds to the "id".
This script works to create the result I want:
dat1 <- dat %>%
mutate(agree4 = ifelse(cat1==4, "1",
ifelse(cat2==4, "1",
ifelse(cat3==4,"1","0")))) %>%
mutate(agree3 = ifelse(cat1==3, "1",
ifelse(cat2==3, "1",
ifelse(cat3==3,"1","0")))) %>%
mutate(agree2 = ifelse(cat1==2, "1",
ifelse(cat2==2, "1",
ifelse(cat3==2,"1","0")))) %>%
mutate(agree1 = ifelse(cat1==1, "1",
ifelse(cat2==1, "1",
ifelse(cat3==1,"1","0")))) %>%
mutate (agree0 = ifelse(cat1==0, "1",
ifelse(cat2==0, "1",
ifelse(cat3==0,"1","0"))))
Here's the function I tried, (as well as numerous other versions trying to create the function for just 1 or 2 additional arguments, and trying different ways to write the function, none of which worked)
myFun <- function (data, agreeNumCol, myCol1, myCol2, myCol3, agreeNum)
data %>%
mutate (agreeNumCol) = ifelse(myCol1 == agreeNum, "1",
ifelse (myCol2 == agreeNum, "1",
ifelse(myCol3 ==agreeNum,"1","0")))
dat2 <- dat %>%
myFun(agree4, cat1, cat2, cat3, 4)
When the function above didn't work, I tried entering inputs using quotes, and various different versions
dat2 <- dat %>%
myFun(agree4, 'cat1', 'cat2', 'cat3', 4)
Which generated the following:
Error in data %>% mutate(agreeNumCol) <- ifelse(myCol1 == agreeNum, "1", :
could not find function "%>%<-"
I would appreciate any guidance here, thank you.
Edited to add what I expect, and now I realize "agree0" is not useful, but this is what I would expect!
expect <- data.frame(
id = c(1, 2, 3, 4, 5, 6),
cat1 = c(4, 0, 1, 0, 4, 4),
cat2 = c(0, 4, 3, 2, 0, 0),
cat3 = c(0, 0, 0, 2, 0, 0),
agree4 = c(1, 1, 0, 0, 1, 1),
agree3 = c(0, 0, 1, 0, 0, 0),
agree2 = c(0, 0, 0, 1, 0, 0),
agree1 = c(0, 0, 1, 0, 0, 0),
agree0 = c(1, 1, 1, 1, 1, 1)
)