开发者

Obtaining index names from a by object by parsing its call

开发者 https://www.devze.com 2023-04-12 07:29 出处:网络
I\'m trying to create an as.data.frame.by method which basically melts the N-dimensional by object for use with latex.table.by.

I'm trying to create an as.data.frame.by method which basically melts the N-dimensional by object for use with latex.table.by.

Melting it is simple enough, since a by object is just a matrix, but then the variable 开发者_如何学Pythonnames returned are the most un-descriptive "X"'s imaginable.

dat <- transform( ChickWeight, Time=cut(Time,3), Chick=cut(as.numeric(Chick),3) )
my.by <- by( dat, with(dat,list(Time,Chick,Diet)), function(x) sum(x$weight) )

Looking through attributes(my.by) doesn't reveal anywhere the index variable names are stored except the call. I'd like to default to something reasonably descriptive for the table.

So that leaves parsing the call:

> attr(my.by,"call")
by.data.frame(data = dat, INDICES = with(dat, list(Time, Chick, 
    Diet)), FUN = function(x) sum(x$weight))
> str(attr(my.by,"call"))
 language by.data.frame(data = dat, INDICES = with(dat, list(Time, Chick,      Diet)), FUN = function(x) sum(x$weight))

I just want the index names used, but I have no idea how to go about parsing this monster. Ideas?


If you make the call with named arguments you get dimnames as you expect:

> my.by <- with(dat, by( weight, list(Time=Time,Chick=Chick,Diet=Diet), sum ))
> str(my.by)
 by [1:3, 1:3, 1:4] 3475 5969 8002 640 1596 ...
 - attr(*, "dimnames")=List of 3
  ..$ Time : chr [1:3] "(-0.021,6.99]" "(6.99,14]" "(14,21]"
  ..$ Chick: chr [1:3] "(0.951,17.3]" "(17.3,33.7]" "(33.7,50]"
  ..$ Diet : chr [1:4] "1" "2" "3" "4"
 - attr(*, "call")= language by.default(data = weight, INDICES = list(Time = Time, Chick = Chick,      Diet = Diet), FUN = sum)


This will work for the example given:

as.character(tail(as.list(attr(my.by, 'call')[['INDICES']]), 1) [[1]]) [-1]

tail(..., 1)[[1]] grabs the list(Time,Chick,Diet), and [-1] drops list.


Hm, the wild guess of attr(my.by,"call")[["INDICES"]] seems to produce a language object.

And coercing that to character works surprisingly well:

> as.character(attr(my.by,"call")[["INDICES"]])
[1] "with"                    "dat"                     "list(Time, Chick, Diet)"

So I could probably grab it from there, although it will remain highly dependent on how the user specifies it. Better parsing ideas would be most appreciated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号