ishido ishido - 1 year ago 59
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?

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download