矩阵的元素为元组

矩阵的元素为元组

本文介绍了在r中创建收益矩阵(矩阵的元素为元组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用R编写囚徒困境代码,但无法创建收益矩阵.想知道是否有一种方法可以创建像数组或元素为元组的矩阵之类的python字典.因此,该矩阵应代表两个参与者的收益:

I'm writing codes for Prisoners' Dilemma in R, and am blocked in creating the payoff matrix. Wonder if there is a way to create a python dictionary like array or a matrix whose elements are tuples. Thus this matrix should represent the gains of both players:

这是图片:

此图像仅是向您显示我在做什么,并且值与我要创建的矩阵不同.我尝试创建列表,然后将它们分配给矩阵,但是它仅将列表的第一个元素分配给矩阵.这是我的代码段:

This image is only to show you what I'm up to, and the values are different from the matrix I want to create.I try to create lists and then assign them to the matrix but it only assigns the first element of lists to the matrix.This is my code snippet:

T=2
R=1
P=0
S=-1


act1 <- as.vector(list(T,S), mode="pairlist")
act2 <- as.vector(list(P,P), mode="pairlist")
act3 <- as.vector(list(R,R), mode="pairlist")
act4 <- as.vector(list(S,T), mode="pairlist")
actions <- c(act3,act4,act1,act2)
payoff.mat <- as.matrix(actions,nrow=2,ncol=2)
dimnames(payoff.mat)[[1]] <- c("Gift","NoGift")
dimnames(payoff.mat)[[2]] = dimnames(payoff.mat)[[1]]

关于如何执行此操作的任何想法?

Any Idea of how to do this?

推荐答案

您的工作已经完成.您只是在尝试清理输出.我将把收益组合到像Python元组这样的对联中,然后从那里创建一个表:

Your work is done already. You are just attempting to clean up the output. I would combine the payoffs in couplets like Python tuples and create a table from there:

T=2
R=1
P=0
S=-1

pair <- function(x,y) sprintf("(%d,%d)", x,y)
all_pairs <- c(pair(T,S), pair(P,P), pair(R,R), pair(S,T))
payoff.mat <- matrix(all_pairs, nrow=2)
dimnames(payoff.mat) <- c(rep(list(c("Gift","NoGift")), 2))

使用Rmarkdown和RStudio,您可以通过在rmarkdown文档中输入上述代码并添加以下内容来以一种不错的格式打印矩阵:

With Rmarkdown and RStudio you can print the matrix in a nice format by entering the above code into an rmarkdown document and adding:

library(knitr)
kable(payoff.mat, format="latex")

有关降价文件的完整解释将超出此问题的范围.有关快速概述,请参见 http://kbroman.org/knitr_knutshell/pages/figs_tables.html

A full explanation of markdown documents would be beyond the scope of this question. For a quick overview see http://kbroman.org/knitr_knutshell/pages/figs_tables.html

这篇关于在r中创建收益矩阵(矩阵的元素为元组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 23:20