ishido ishido - 3 months ago 12
R Question

How to get levels of a column based on a condition regarding another column

If there is a data frame that looks like:

datas$A <- c("M","M","F","M","F","U","U")
datas$B <- c("cat","dog","cat","dog","cat","dog","dog")

I would like to do something along the lines of:

list_levels <- levels(datas$A where datas$B == "cat")

as output:

"M" "F"

how would I proceed in doing this?

list_levels <- unique(df$A[df$B == "cat"])
# [1] "M" "F"

Note that when you use unique(), it will return the unique values in the order they appear in df$A and not in alphabetical order.