Antoni Parellada
Antoni Parellada

Reputation: 4821

How can I change the indices of an R vector?

I would like to plot as lines the results of different random vectors (look at them like random walks), such that each one of them follows in a sequence after the previous one.

To do so, I'd like the indexing of the second vector to start where the first one ended.

For instance in the case of

a <- cumsum(rnorm(10))
b <- cumsum(rnorm(10))
head(a)
[1] -0.03900184 -0.37913568 -0.42521156
head(b)
[1]  1.3861861 -0.2418804  1.1159065

Both vectors are naturally indexed from [1] to [10]. So if I plot them, they overlap (left plot), while what I would like is for b to follow a in the x-axis (right plot):

plot(a, type = "l", xlim=c(0,20), ylim=c(-10,10), xlab="", ylab="", col=2)
lines(b, col=3)

enter image description here

Appending b to a seems to be an avenue, but when I subset the resulting vector, I end up again with a vector that starts at zero...

Upvotes: 2

Views: 1899

Answers (4)

Dra
Dra

Reputation: 11

If the data point index is important for you I am assuming you are working with a time series type data. You should consider time series indexing of your object creation and subsetting for desired manipulation. Here is an example

foo <- ts(1:10, frequency = 1, start = 1)

# Subset using time series indexing
foo1 <- ts(foo[1:5], start = index(foo)[1], frequency = frequency(foo))
foo6 <- ts(foo[6:10], start  = index(foo)[6], frequency = frequency(foo))

# Combine using appropriate index    
fooNew <- ts(c(foo1, foo6), start = start(foo1), frequency = frequency(foo1))

Upvotes: 0

Maurits Evers
Maurits Evers

Reputation: 50738

What about something like this using ggplot2?

library(tidyverse);
set.seed(2017);
a <- cumsum(rnorm(10))
b <- cumsum(rnorm(10))
stack(data.frame(a, b)) %>%
    rowid_to_column("x") %>%
    ggplot(aes(x, values)) +
    geom_line(aes(colour = ind))

enter image description here

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389325

We can create a new b with NAs till length(a) -1 and then add last value of a and then append b and then use this new_b in lines argument.

set.seed(1)

a <- cumsum(rnorm(10))
b <- cumsum(rnorm(10))

new_b <- c(rep(NA, length(a)-1),a[length(a)], b)

plot(a, type = "l", xlim=c(0,20), ylim=c(-10,10), xlab="", ylab="", col=2)
lines(new_b, col=3)

enter image description here

Upvotes: 0

www
www

Reputation: 39174

You can specify the x argument in the lines function.

set.seed(146)

a <- cumsum(rnorm(10))
b <- cumsum(rnorm(10))

plot(a, type = "l", xlim=c(0,20), ylim=c(-10,10), xlab="", ylab="", col=2)
lines(x = 10:19, y = b, col=3)

enter image description here

Upvotes: 2

Related Questions