Rembrandt Q. Einstein - 8 months ago 54

R Question

I want to use iteration to turn the entries in a list into a 2x2 matrix, and then assign the same column and row names to these tables, as well as integer values for the matrix cells.

For examples sake let's pretend this is the list with the entries whose names I want to turn into matrices:

`cnames <- c("Honda", "Toyota", "Nissan")`

Creating the tables themselves seem to work fine with the assign function:

`for (i in 1:length(cnames)){`

assign(paste(cnames[i],"table",sep="_"), matrix(,nrow=2,ncol=2))

}

Which when I type, for instance:

`> Honda_table`

...returns:

`[,1] [,2]`

[1,] NA NA

[2,] NA NA

But if in the original iterative function I try to assign column names, like such:

`for (i in 1:length(cnames)){`

assign(paste(cnames[i],"table",sep="_"), matrix(,nrow=2,ncol=2))

colnames(paste(cnames[i],"table",sep="_")) <- c("A","B")

}

...I get this error instead:

`Error : attempt to set 'colnames' on an object with less than two dimensions`

I don't understand why this is coming up, since after using the original assign function, if I look up the dimensions any of the tables, such as:

`>dim(honda_table)`

...I get:

`[1] 2 2`

Which indicates it is a 2x2 dimensional object.

Moreover, I cannot assign pre-set values to the matrix cells, like so:

`for (i in 1:length(cnames)){`

assign(paste(cnames[i],"table",sep="_"), matrix(,nrow=2,ncol=2))

paste(cnames[i],"table",sep="_")[1,1] = 1

}

...without getting this error:

`Error : incorrect number of subscripts on matrix`

What is going on here?

Thanks.

Answer

I am not sure it is the best, and the most beautiful, way but seems to work:

```
for (i in 1:length(cnames)){
tab<- matrix(,nrow=2,ncol=2)
colnames(tab)<- c("A","B")
assign(paste(cnames[i],"table",sep="_"), tab)
}
rm(tab)
```

Source (Stackoverflow)