New column with dplyer (if X, then return A; if other than X, B)

Need help w/ the "mutate" function in dplyer.

Let's say I've got educational data, w/ five classrooms: A, B, C, D, and E. Classrooms A, B, and C are on Campus 1, and D and E are on Campus 2. My understanding is that I should be able to use "mutate" to tell R, "hey, if the letter is D or E, assign the classroom to Campus 2; if not, assign it to Campus 1" and have a new column with Campus info created.

But I've been Googling, and I can't find the code for this; the only examples of "mutate" I see are adding / subtracting / dividing one column by another.

Help? I have thousands of rows, so entering things by hand is not a possibility. My prof specifically said I'd use dplyer for this, rather than some other package, but she did not give us the code and I'm turning up a lot of dead ends.

Try combining mutate() with case_when(). Both are dplyr functions.

FWIW, you could also do this with ifelse, a base R function. Assuming that classroom is a string and not a factor:

mutate(df, campus = ifelse(classroom %in% LETTERS[1:3], 1, 2))

If classroom is a factor, you could use the same code, but with as.character(classroom).

I agree with @siddharthprabhu.

something like this mutate(campus = case_when(classroom <=3 ~ 1, classroom>=4 ~2)

Hope it helps

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.