[R] Question about NULL matrix? Can I define a NULL matrix in R?
David Winsemius
dwinsemius at comcast.net
Thu Aug 11 04:37:13 CEST 2011
On Aug 10, 2011, at 10:03 PM, Rolf Turner wrote:
> On 11/08/11 13:27, David Winsemius wrote:
>>
>> On Aug 10, 2011, at 9:22 PM, Rolf Turner wrote:
>>
>>> On 11/08/11 13:11, David Winsemius wrote:
>>>>
>>>> On Aug 10, 2011, at 8:23 PM, Andra Isan wrote:
>>>>
>>>>> Hi All,
>>>>> I would like to create a matrix in R but I dont know the size of
>>>>> my matrix. I only know the size of the columns but not the size
>>>>> of the rows. So, is there any way to create a dynamic matrix of
>>>>> size NULL by n_cols? and then add to that matrix?
>>>>> I know for a vector, I can do this: x= NULL but is there any way
>>>>> to do the same for a matrix as well?
>>>>
>>>> No. You cannot make an R matrix without knowing the number of
>>>> rows. By definition an R matix has two integer dimensions.
>>>> Alternatives: You can rbind to an existing matrix, or you can
>>>> make a larger than necessary matrix filled with NA's and then
>>>> fill and later extract a subset of the rows.
>>>>
>>>
>>> Wrong-oh, David. :-) Check this out:
>>
>> 0 is an integer.
>
> Yes it is. But you are being pedantic. My suggestion does exactly
> what I am sure the OP wanted.
> He used the phrase ``NULL by n_cols'' simply because of unclear
> thinking. What he wanted was an
> ``empty matrix'', with no rows and a given number of columns. Which
> is what I gave him.
He asked for a "dynamic matrix", by which I imagined (in the absence
of an example) that he wanted to be able to define a matrix and then
assign values to rows without allocating any rows. Your zero row
matrix does not accomplish what I imagined his request to represent.
Your offering is rather useless unless you want to adopt what I
suggested as one strategy:
> m <- matrix(0,nrow=0,ncol=5)
> m[1,1] <- 1
Error in m[1, 1] <- 1 : subscript out of bounds
Alternative 1:
> m <- rbind(m, c(1,NA,NA,NA,NA) )
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 1 NA NA NA NA
>
> It is interesting that the syntax works with matrices but not with
> data frames. If you want an
> empty data frame, with no rows and a given number of columns, you
> need to create a matrix,
> in the manner indicated, and then use as.data.frame, which yields
> the desired result.
>
> cheers,
>
> Rolf
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list