So I am going to be doing some work with R soon, and I need to learn how to use it. I figured a good exercise would be to try to write a program that takes a payoff matrix and does iterated elimination of dominated strategies (if you don’t know what I’m talking about, it’s very simple game theory stuff and not really important to the question). The first step was to write a function that takes a matrix and returns a summary of all strategies that are dominated, but something is going wrong.
strictdomlist <- function(m) {
# takes a matrix, determines if row player has strictly
# dominated strategies
strategies <- dim(m)[1]
dominatingstrategies <- list()
for (i in 1:strategies) {
dstrat <- 0
for (j in 1:strategies) {
if (i != j) {
if (all(m[i, ]<m[j, ])) dstrat <- c(dstrat,j)
}
}
dominatingstrategies[i] <- dstrat
}
return(dominatingstrategies)
}
All (I wish) it’s doing is checking each row to see if there is a row which has entries that are all greater. If there is, it should put the number of that row in a vector, and then at the end, assign that vector to the i-th position in dominatingstrategies. If I give it this matrix:
[,1] [,2] [,3] [,4]
[1,] 1 4 2 10
[2,] 2 5 9 11
[3,] 0 1 1 1
[4,] 16 7 10 12
I want it to give me back:
[[1]]
[1] 2 4
[[2]]
[1] 4
[[3]]
[1] 1 2 4
[[4]]
[1] 0
But what it’s giving me is:
> strictdomlist(m2)
[[1]]
[1] 4
[[2]]
[1] 4
[[3]]
[1] 4
[[4]]
[1] 0
Warning messages:
1: In dominatingstrategies[i] <- dstrat :
number of items to replace is not a multiple of replacement length
2: In dominatingstrategies[i] <- dstrat :
number of items to replace is not a multiple of replacement length
3: In dominatingstrategies[i] <- dstrat :
number of items to replace is not a multiple of replacement length
Can anyone see what I’m doing wrong? And, if there’s a better way of doing this in R, can you help?
Thank you!
It’s your list assignment:
To assign into a list, you have to use double square brackets:
When you use single brackets, you extract the list containing the vector contained in
dominatingstrategies[i], not the vctor itself.Also, since you start your
dstratat 0, you get this matrix out (with the above error fixed):i.e., you get a
0out in every element, including ones which have greater rows.If you don’t want this, you can initialise
dstratasdstrat <- c(), and then at the end do something like