[R] On "^" returning a matrix when operated on a data.frame
Duncan Murdoch
murdoch.duncan at gmail.com
Thu Nov 14 00:32:34 CET 2013
On 13-11-13 6:00 PM, Arunkumar Srinivasan wrote:
> Dear R-users,
>
> I am wondering why "^" operator alone returns a matrix, when operated on a data.frame (as opposed to all other arithmetic operators). Here's an example:
>
> DF <- data.frame(x=1:5, y=6:10)
> class(DF*DF) # [1] data.frame
> class(DF^2) # [1] matrix
>
> I posted here on SO: http://stackoverflow.com/questions/19964897/why-does-on-a-data-frame-return-a-matrix-instead-of-a-data-frame-like-do and got a very nice answer - it happens because a matrix is returned (obvious by looking at `Ops.data.frame`). However, what I'd like to understand is, *why* a matrix is returned for "^" alone? Here's an excerpt from Ops.data.frame (Thanks to Neal Fultz):
>
> if (.Generic %in% c("+", "-", "*", "/", "%%", "%/%")) {
> names(value) <- cn
> data.frame(value, row.names = rn, check.names = FALSE,
> check.rows = FALSE)
> }
> else matrix(unlist(value, recursive = FALSE, use.names = FALSE),
> nrow = nr, dimnames = list(rn, cn))
>
>
> It's clear that a matrix will be returned unless `.Generic` is one of those arithmetic operators. My question therefore is, is there any particular reason why "^" operator is being missed in the if-statement here? I can't think of a reason where this would break. Also ?`^` doesn't seem to mention anything about this coercion.
It's not just ^ that is missing, the logical relations like <, ==, etc
also return matrices. This is very old code (I think from 1999), but I
would guess that the reason is that the ^ and < operators always return
values of a single type (numeric and logical respectively), whereas the
other operators can take mixed type inputs and return mixed type outputs.
Duncan Murdoch
> Please let me know if I should be posting this to R-devel list instead.
>
> Thank you very much,
> Arun
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
>
More information about the R-help
mailing list