[R] Large matrix into a vector
Marc Schwartz
marc_schwartz at comcast.net
Thu Mar 29 15:27:35 CEST 2007
On Thu, 2007-03-29 at 02:12 -0700, A Ezhil wrote:
> Hi All,
>
> Thank you very much for all your suggestions. It's a
> great learning for me. All the three suggested
> solutions seem working. I don't know what 'side
> effects' that you were talking about.
As Peter noted, the phrase 'side effect' may be sub-optimal.
However, I would use the interpretation that in this case, the removal
of dim attributes on a single object as a consequence of the use of c(),
though documented, is not the primary intended purpose of the function.
Stated differently, perhaps in a manner consistent with Prof. Ripley's
reply, the coercion of a matrix to a vector by the use of c(), is
applying a function to an object to gain the benefit of behavior that is
secondary to the intended functionality of combining objects.
> To summarize the
> responses:
>
> > s <- read.table("sample.txt", sep="\t")
> > s1 <- as.matrix(s)
> > s1
> V1 V2 V3
> 1 0.59 0.47 0.44
> 2 0.85 0.42 0.57
> 3 0.48 0.57 0.57
> 4 0.61 0.24 0.24
> 5 0.38 0.21 0.36
> 6 0.65 0.42 1.50
> 7 0.49 0.23 0.42
> 8 0.60 0.51 0.53
> 9 0.00 0.00 0.00
>
> > s2 <- as.vector(s1)
> > s2
> [1] 0.59 0.85 0.48 0.61 0.38 0.65 0.49 0.60 0.00 0.47
> 0.42 0.57 0.24 0.21 0.42 0.23 0.51 0.00 0.44 0.57 0.57
> 0.24 0.36
> [24] 1.50 0.42 0.53 0.00
> > s3 <- c(s1)
> > s3
> [1] 0.59 0.85 0.48 0.61 0.38 0.65 0.49 0.60 0.00 0.47
> 0.42 0.57 0.24 0.21 0.42 0.23 0.51 0.00 0.44 0.57 0.57
> 0.24 0.36
> [24] 1.50 0.42 0.53 0.00
> > s3 <- s1
> > dim(s3) <- NULL
> > s3
> [1] 0.59 0.85 0.48 0.61 0.38 0.65 0.49 0.60 0.00 0.47
> 0.42 0.57 0.24 0.21 0.42 0.23 0.51 0.00 0.44 0.57 0.57
> 0.24 0.36
> [24] 1.50 0.42 0.53 0.00
>
> Interestingly, if I apply the same three solutions to
> the data.frame 's', the results are different: (1)
> as.vector() keeps the data frame as it is. (2) c()
> changes into lists, and (3) making dim() <- NULL keeps
> as structure.
That's because the underlying structure of a data frame is a list,
whereas a matrix is a vector.
HTH,
Marc
<snip>
More information about the R-help
mailing list