lists as matrix cells ?
A matrix may only contain one data type. By not specifying when you created m, it was filled with logical values of NA. A logical value can't hold a list. You can see that with str(m) which returns:
str(m)
logi [1:3, 1:2] NA NA NA NA NA NA
- attr(*, "dimnames")=List of 2
..$ : chr [1:3] "Row_one" "Row_two" "Row_three"
..$ : chr [1:2] "Column_A" "Column_B"
If you were to instead specify that the elements of m should be list objects:
m <- matrix(list(), nrow=3, ncol=2,
dimnames=list(
c("Row_one", "Row_two", "Row_three"),
c("Column_A", "Column_B")
)
)
(and check with str(m) again)
then you can replace those list objects with other list objects
m[[ 1,1 ]] <- list(1.0, 2.0)
Please also note that [ and [[ are not the same thing.
I'm not sure this is the most efficient solution for your problem, but
since I'm not really sure what your problem is I solved the question
asked rather than the underlying problem.
Sarah
On Wed, Nov 21, 2012 at 11:11 AM, Asis Hallab <asis.hallab at gmail.com> wrote:
Dear R experts,
since more or less half a year I am using R.
In many of my computations I construct huge matrices. Often I do so using
'cbind' on named lists:
do.call( 'cbind',
list(
"Column_A"=list("Row_one"=1.0, "Row_two"=2.0, "Row_three"=3.0),
"Column_B"=list("Row_one"=4.0, "Row_two"=5.0, "Row_three"=6.0)
)
)
# Returns:
Column_A Column_B
Row_one 1 4
Row_two 2 5
Row_three 3 6
In some cases I even construct matrices with lists as cell content:
do.call( 'cbind',
list(
"Column_A"=list("Row_one"=list(1.0, 2.0), "Row_two"=list(2.0, 3.0),
"Row_three"=list(3.0, 4.0)),
"Column_B"=list("Row_one"=list(4.0, 5.0), "Row_two"=list(5.0, 6.0),
"Row_three"=list(6.0, 7.0))
)
)
# Returns:
Column_A Column_B
Row_one List,2 List,2
Row_two List,2 List,2
Row_three List,2 List,2
Interestingly I seem not to be able to initialize a 3*2 matrix and
subsequently fill its cells with lists in order to produce the latter
example:
m <- matrix( nrow=3, ncol=2,
dimnames=list(
c("Row_one", "Row_two", "Row_three"),
c("Column_A", "Column_B")
)
)
# Returns:
Column_A Column_B
Row_one NA NA
Row_two NA NA
Row_three NA NA
# The following expressions produce the same error:
m[ "Row_one", "Column_A" ] <- list(1.0, 2.0)
m[[ "Row_one", "Column_A" ]] <- list(1.0, 2.0)
m[ 1,1 ] <- list(1.0, 2.0)
m[[ 1,1 ]] <- list(1.0, 2.0)
# Error returned by each of the above expressions:
*number of items to replace is not a multiple of replacement length*
*So, now my questions:*
*1)* What am I doing wrong? How to get the above to work?
*2)* Or am I misusing matrices in R? Is it just by coincidence ( bug ) that
my 'cbind' or 'rbind' calls can generate matrices with lists as cell
content, while I seem not to be able to do so by direct assignment (as in
above example expressions)?
Any ideas, comments and help will be much appreciated!
Kind regards!
Josef
-- Sarah Goslee http://www.functionaldiversity.org