简体   繁体   中英

R: convert vectors of different lengths into a fixed time interval

I am working with 2 vectors with different lengths 105,102 . Call them y1,y2

Although they are different in length, each vector represents activity that happens in 30 seconds.

Assume the first element of all vectors start at time = 0 seconds, I was able to plot them out with the following code:

y1 <- plot(seq(0,100,length = 105), rnorm(length(seq(0,100,length = 105))), type = "l")
y2 <- plot(seq(0,100,length = 102), rnorm(length(seq(0,100,length = 102))), type = "l")
l <- length(y1)
x <- seq(0,l,length= l)
y <- y1
plot(x, y, type = "l", xlab = "time", ylab = "bla")


l <- length(y2)
x <- seq(0,l,length= l)
y <- y2
lines(x,y, type = "l")

Now the above code will produce a graph with x-axes ranging from $(0,105)$. However, I want the x-axes to display $(0, 30)$ seconds.

I know the major problem is that the two vectors are in different lengths, but suppose I want to split the elements of each vector along the time interval $0 - 30$ seconds.

How should I approach this ?

I think OP's just looking to equally distribute each y vector in time interval of 30 sec and plot the same. In that case, following should do the trick. Essentially, for x argument of plot and lines function, we need to provide vector which has number of elements equal to number of elements in y corresponding argument, spread out from 0 to 30.

set.seed(1234)
y1 <- rnorm(length(seq(0,100,length = 105)))
y2 <- rnorm(length(seq(0,100,length = 102)))
plot((30/length(y1))*seq_along(y1), y1, type = 'l',col='red', xlab='time', ylab='y')
lines((30/length(y2))*seq_along(y2), y2, col='green')

which gives

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM