ishido ishido - 1 month ago 4
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:

list_levels
"M" "F"


how would I proceed in doing this?

Answer
list_levels <- unique(df$A[df$B == "cat"])
print(list_levels)
# [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.

Comments