Hi Spencer,
One piece is that a data frame of the same dimensions as went in comes out.
The second piece is that the vector is recycled.
So in your first example:
data.frame(1) * 1:4
you only end up with the first element:
data.frame(1) * 1
If you try:
data.frame(1) * 4:1
you get a data frame with a value of 4.
Now for:
data.frame(1:2, 3:4) * 5:7
recycling kicks in again, and you get:
1 * 5, 2 * 6, 3 * 7, and 4 * 5
When working with vectors, you get recycling and it expands to the greater
length vector:
1:3 * 1:6
has length 6. But data frames are sort of a 'higher' class and the
dimensions of the data frame trump the vector.
A slightly different behavior is observed for matrices:
matrix(1:6, ncol=2) * 1:3
Gives recycling as expected to the longer of the vectors, but
matrix(1:6, ncol=2) * 1:9
gives an error, but the error is _not_ directly in the multiplication, as
it were, but rather the results (which because matrices are stored as
vectors has expanded to be the length of the longer vector, here 1:9) do
not match the input dimensions of the matrix. In particular, this is the
same as trying to do:
x <- 1:9
attributes(x)$dim <- c(3, 2)
Error in attributes(x)$dim <- c(3, 2) :
dims [product 6] do not match the length of object [9]
basically, R gets the result of 1:6 * 1:9, but then cannot format it back
as a matrix, because the saved dimensions do not fit the new resulting
data. You can verify that R does indeed to the calculations if you go
under the hood --- the multiplication is done, and then it tries to apply
the dims and it errors out.
Cheers,
Josh
On Wed, Apr 2, 2014 at 11:42 PM, Spencer Graves <
spencer.graves@structuremonitoring.com> wrote:
> Hello, All:
>
>
> What's the logic behind "data.frame(1)*1:4" producing a scalar 1?
> Or the following:
>
>
> data.frame(1:2, 3:4)*5:7
> X1.2 X3.4
> 1 5 21
> 2 12 20
>
>
> I stumbled over this, because I thought I was multiplying a scalar
> times a vector, and obtaining a scalar rather than the anticipated vector.
> I learned that my "scalar" was in fact a data.frame with one row and one
> column.
>
>
> What am I missing?
>
>
> Thanks,
> Spencer
>
> ______________________________________________
> R-help@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.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://joshuawiley.com/
Senior Analyst - Elkhart Group Ltd.
http://elkhartgroup.com
260.673.5518
[[alternative HTML version deleted]]