Reputation: 1274
Good afternoon ,
Assume we have the following list :
L1=list(y1 = structure(c(2L, 2L, 5L, 3L, 3L, 4L), .Dim = 2:3, .Dimnames = structure(list(
c("PURPLE", "YELLOW"), c("1", "2", "3")), .Names = c("",
"")), class = "table"), y2 = structure(c(3L, 1L, 5L, 3L, 2L,
5L), .Dim = 2:3, .Dimnames = structure(list(c("LARGE", "SMALL"
), c("1", "2", "3")), .Names = c("", "")), class = "table"),
y3 = structure(c(2L, 2L, 3L, 5L, 3L, 4L), .Dim = 2:3, .Dimnames = structure(list(
c("DIP", "STRETCH"), c("1", "2", "3")), .Names = c("",
"")), class = "table"), y4 = structure(c(3L, 1L, 4L, 4L,
4L, 3L), .Dim = 2:3, .Dimnames = structure(list(c("ADULT",
"CHILD"), c("1", "2", "3")), .Names = c("", "")), class = "table"),
y5 = structure(c(3L, 1L, 5L, 3L, 4L, 3L), .Dim = 2:3, .Dimnames = structure(list(
c("FALSE", "TRUE"), c("1", "2", "3")), .Names = c("",
"")), class = "table"))
#output
> L1
$y1
1 2 3
PURPLE 2 5 3
YELLOW 2 3 4
$y2
1 2 3
LARGE 3 5 2
SMALL 1 3 5
$y3
1 2 3
DIP 2 3 3
STRETCH 2 5 4
$y4
1 2 3
ADULT 3 4 4
CHILD 1 4 3
$y5
1 2 3
FALSE 3 5 4
TRUE 1 3 3
For each variable $y , I tried to get the modalities that are the most frequent ( for each column). For each column , i tried to retrieve the row with the maximum frequency as following :
lapply(res, function(x) max.col(t(x)))
$y1
[1] 2 1 2
$y2
[1] 1 1 2
$y3
[1] 1 2 2
$y4
[1] 1 1 1
$y5
[1] 1 1 1
Now , i need to get the associated modalities , for example :
$y1
[1] YELLOW PURPLE YELLOW
$y2
[1] LARGE LARGE SMALL
...
I tried without success : lapply(res, function(x) rownames(max.col(t(x))))
Thank you for help !
Upvotes: 1
Views: 30
Reputation: 39667
You have to subset rownames(x)
with the index, and not call it with the index, to get the names.
lapply(L1, function(x) rownames(x)[max.col(t(x))])
#$y1
#[1] "PURPLE" "PURPLE" "YELLOW"
#
#$y2
#[1] "LARGE" "LARGE" "SMALL"
#
#$y3
#[1] "DIP" "STRETCH" "STRETCH"
#
#$y4
#[1] "ADULT" "ADULT" "ADULT"
#
#$y5
#[1] "FALSE" "FALSE" "FALSE"
Upvotes: 2