Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create sequences with pdl?

Tags:

r

perl

pdl

I trying to translate part of my R code to perl with pdl, and I would like to know if pdl has any syntax for creating sequences (besides the trivial my $xx=pdl(1..20))

something like having a vector ['a','b'] rep 20 => a,b,a,b,a,b.... 20 times? [EDIT]: The basic repeats can be done with normal Perl repeat string x operator but I am looking for something like the rep() and seq() in R:

[R]
> rep(1:3, each=2, times=3)
1 1 2 2 3 3 1 1 2 2 3 3 1 1 2 2 3 3
> rep(1:4, c(1,2,3,2))
1 2 2 3 3 3 4 4
> seq(0,12,3)
0 3 6 9 12
like image 855
Pablo Marin-Garcia Avatar asked Dec 22 '22 11:12

Pablo Marin-Garcia


1 Answers

Well, I only just started using PDL but from what I've seen and used, it doesn't seem like PDL is really what you want for making sequences. You're probably better off using perl's range operator (..) with any combination of map, grep, and x.

That said, if you were really determined to use PDL for some reason, you could probably use the sequence function and then twiddle the piddle until it looks like what you want:

pdl> p sequence(10)

[0 1 2 3 4 5 6 7 8 9]


pdl> p sequence(2,4) #Slice column 1 for evens, 2 for odds.

[
 [0 1]
 [2 3]
 [4 5]
 [6 7]
]


pdl> p sequence(3,4) * 5 #Multiply to step by an amount.

[
 [ 0  5 10]
 [15 20 25]
 [30 35 40]
 [45 50 55]
]

You could also use slices to grab columns as a way to step along a sequence.

For anything else, such as what you're doing in your R examples, you'd need to start getting creative:

pdl> p $a = (yvals zeroes(2,3))+1

[
 [1 1]
 [2 2]
 [3 3]
]

pdl> p pdl($a,$a,$a)->flat #-> rep(1:3, each=2, times=3)
[1 1 2 2 3 3 1 1 2 2 3 3 1 1 2 2 3 3]

(The above would be shorter if I knew how to more easily duplicate matrixes) [edit] It seems that's easily done with dummy! $a = (zeroes(2,3)->yvals + 1)->dummy(2,3)->flat

Once again, unless you have a specific need to do this I think it would be best to use perl for making your sequences.

[edit]Here's how you'd do that: Note that 'x' is not just a string multiplier, it also multiplies lists. You need to explicitly use brackets around your vars to inform perl that x is being used on a list.

#> rep(1:3, each=2, times=3)
my @s = map {($_) x 2} (1..3) x 3;

#> seq(0,12,3)
my @s = map {$_ * 3} 0..12/3;

#> rep(1:4, c(1,2,3,2))
#Ewww. So you basically want to multiply one list by another list.
#Here's one way to do it:
use List::MoreUtils qw(pairwise);
my @s = &pairwise(sub {($a) x $b}, [1..4], [1,2,3,2])
like image 152
Jarrod Funnell Avatar answered Dec 24 '22 00:12

Jarrod Funnell