I am trying to get the name of a data.frame column based on its contents in R. For instance, in
dd= data.frame(col1=c(1,2,3), col2=c(4,5,6), col3=c(4,4,4))
I am looking for a something that returns col1
when I feed it c(1,2,3)
.
I found this advice elsewhere but it does not work for me; when, as suggested, I try this
colnames(dd)[which(dd == c(1,2,3), arr.ind = TRUE)]
colnames(dd)[which(dd == c(1,2,3), arr.ind = TRUE)[2]]
it returns all kinds of things, here the result for the 1st:
[1] "col1" "col2" "col3" "col1" "col1" "col1"
What is the best way to do this?
Is the above approach right; can you explain what exactly it does?
I was surprised not to find anything on this here; if it's a duplicate, I'd be glad for links / search terms.