I have a data set including two categorical variables, name
and position
. Every level of name
corresponds to a single level of position
, but every level of position
corresponds to multiple levels of name
.
data <- data.frame(
name = factor(rep(1:8, each=2)),
position = rep(c("A", "B", "C", "D", "B", "D", "A", "C"), each=2)
)
table(data$name, data$position)
Table output is:
A B C D
1 2 0 0 0
2 0 2 0 0
3 0 0 2 0
4 0 0 0 2
5 0 2 0 0
6 0 0 0 2
7 2 0 0 0
8 0 0 2 0
I'd like to return a list or table of the position
levels that correspond to each name
level (I'm not picky about the format). For the example above, the desired output could look like:
1 2 3 4 5 6 7 8
"A" "B" "C" "D" "B" "D" "A" "C"
In this example you could shortcut it by taking all the even or odd values of position
but that's not an option for my data frame since the number of cases per level of name
varies.
Thanks in advance for helping an R newbie out. I imagine that there is a straightforward function to do this, but I don't know its name to search for it.
CodePudding user response:
colnames(a<-table(data))[max.col(a)]
[1] "A" "B" "C" "D" "B" "D" "A" "C"