weicheng wang
2009-Apr-07 19:32 UTC
[R] use the value of variable to quote certain elements in matrix
Hi, I want to use the value of variable to quote elements in matrix. For example, I have a matrix like: y1 y2m1 1 2m2 3 4 where y1,y2,m1,m2 are column and row names. I have two random character variable, say x, that could be either y1 or y2 and y that could be either m1 or m2. So can I do like Matrix[y,x] to quote elements? I've tried this way but it simply use "x" and "y" itself rather its value as column or row names. I want to use the value of x and y as colunm or row names. So when x="y1" and y="m1" in cases, I want to matrix[x,y]=1. please help. [[alternative HTML version deleted]]
Luc Villandre
2009-Apr-07 20:05 UTC
[R] use the value of variable to quote certain elements in matrix
Hi Weicheng, Did you forget to add " " to index your elements? The following example works perfectly fine. test.matrix = matrix(1:4,nrow=2) ; rownames(test.matrix)=c("hi1","hi2") ; colnames(test.matrix)=c("bye1","bye2") ; test.matrix bye1 bye2 hi1 1 3 hi2 2 4 test.matrix["hi1","bye2"] ; [1] 3 ran.row = sample(x=rownames(test.matrix),size=1) ; ran.col = sample(x=colnames(test.matrix),size=1) ; test.matrix[ran.row,ran.col] ; Is this in a way what you were trying to get? Best of luck, Luc weicheng wang wrote:> Hi, I want to use the value of variable to quote elements in matrix. > For example, I have a matrix like: > y1 y2m1 1 2m2 3 4 > where y1,y2,m1,m2 are column and row names. I have two random character variable, say x, that could be either y1 or y2 and y that could be either m1 or m2. So can I do like Matrix[y,x] to quote elements? I've tried this way but it simply use "x" and "y" itself rather its value as column or row names. I want to use the value of x and y as colunm or row names. So when x="y1" and y="m1" in cases, I want to matrix[x,y]=1. > please help. > > > > > [[alternative HTML version deleted]] > > > ------------------------------------------------------------------------ > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >