[R] behavior of seq_along

0 views
Skip to first unread message

Dale Steele

unread,
Feb 25, 2010, 9:02:01 AM2/25/10
to R-h...@r-project.org
I'm trying to understand the behavior of seq_along in the following example:

x <- 1:5; sum(x)
y <- 6:10; sum(y)

data <- c(x,y)
S <- sum( data[seq_along(x)] )
S
T <- sum( data[seq_along(y)] )
T

Why is T != sum(y) ?

______________________________________________
R-h...@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.

Dieter Menne

unread,
Feb 25, 2010, 9:15:46 AM2/25/10
to r-h...@r-project.org

Dale Steele wrote:
>
>
> x <- 1:5; sum(x)
> y <- 6:10; sum(y)
>
> data <- c(x,y)
> S <- sum( data[seq_along(x)] )
> S
> T <- sum( data[seq_along(y)] )
> T
>
>

If in doubt, divide and conquer:

seq_along(x)
[1] 1 2 3 4 5
> seq_along(y)
[1] 1 2 3 4 5

You expected that the second vector is 6,7...
Dieter

--
View this message in context: http://n4.nabble.com/behavior-of-seq-along-tp1569033p1569049.html
Sent from the R help mailing list archive at Nabble.com.

Henrique Dallazuanna

unread,
Feb 25, 2010, 9:08:32 AM2/25/10
to Dale Steele, R-h...@r-project.org
Because,

data[seq_along(x)] == data[seq_along(y)],

You need this:

sum(data[length(x) + seq_along(y)])

--
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O

David Winsemius

unread,
Feb 25, 2010, 9:55:18 AM2/25/10
to Dale Steele, R-h...@r-project.org

On Feb 25, 2010, at 9:02 AM, Dale Steele wrote:

> I'm trying to understand the behavior of seq_along in the following
> example:
>
> x <- 1:5; sum(x)
> y <- 6:10; sum(y)
>
> data <- c(x,y)
> S <- sum( data[seq_along(x)] )
> S
> T <- sum( data[seq_along(y)] )
> T
>
> Why is T != sum(y) ?

Look at

seq_along(y)

seq_along returns indices for the purpose of accession of elements, so
it starts with 1 and ends with the length of the object.

Had you asked for sum(data[y[seq_along(y)]]) you might have achieved
your expectation.

>
> ______________________________________________
> R-h...@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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT

Reply all
Reply to author
Forward
0 new messages