Skip to content

seq_along and rep_along

6 messages · Duncan Murdoch, Hadley Wickham, robin hankin

#
Hi all,

A couple of ideas for improving seq_along:

* It would be really useful to have a second argument dim:

    seq_along(mtcars, 1)
    seq_along(mtcars, 2)
    # equivalent to
    seq_len(dim(mtcars)[1])
    seq_len(dim(mtcars)[2])

  I often find myself wanting to iterate over the rows or column of a
data frame, and there isn't a particularly nice idiom if you want to
avoid problems with zeros - you have to use seq_len(nrow(df)) etc

* To me, it would seem be very natural to have a rep_along function:

  rep_along <- function(x, y) rep(x, length.out = length(y))

  possibly with more checking for the case where the lengths aren't
integer multiples.

I'd be happy to submit proposed implementations/documentation if there
was interest.

Hadley
#
On 12-01-06 1:31 PM, Hadley Wickham wrote:
I don't see the benefit of seq_along(mtcars, 1) versus seq_len(nrow(df)) 
in readability.

Duncan Murdoch
#
I like it because:

* it reads nicely: I want a sequence along this structure in that direction
* it's more consistent: for(i in seq_along(x)) -> for(row in
seq_along(mtcars, 1))
* it generalised in a straightforward way to arrays

I don't think it's a huge improvement, but it is frustrating when base
functionality only works with vectors, not matrices, or arrays. It
would be more compelling if (e.g.) t and rev also had dimension
arguments.

Hadley
2 days later
#
hello folks

[snip]
well put!  I would add, though, that t() generalizes to aperm(),
and the magic package contains  arev()  which is a generalization
of rev().

I'm always on the lookout for other array functionality of this type
that might sit well with magic.  Anyone?

best wishes

Robin

  
    
#
There are the flip operators of matlab, and rotating matrices/array by
multiples of 90 degrees.
Have you considered pulling out the matric manipulation functions from
magic?  I think they'd do well in their own package, and would be more
findable.

Hadley
#
hello Hadley

thanks for this...
arot() in the magic package does this (which is an operation
frequently encountered in magic hypercubes)
That is a very good idea.  I have fought shy of this because the array
functionality of the magic package didn't seem to be enough to
justify a package of its own, but maybe that isn't true any more.
And I must say that the majority of user comments on the magic package
are in relation to functions such as arot() and adiag()  and apad()
and aplus() etc etc that are not specific to magic hypercubes.

Does the List have any comments?

rksh