I would like to replicate a function that simulates time series data with different size of cases nested in clusters. Here is the code to do that:
tsfunc <- function (size=10) {
ar.epsilon <- arima.sim(list(order = c(1,0,0), ar = 0.7), n = size, sd=20)
x=rnorm(size)
y=as.numeric(50 + 25*x + ar.epsilon)
data.frame(id=1:size, x=x, y=y)}
df1 <- data.frame(cluster=1,tsfunc(10))
names(df1) <- c("cluster","id","x","y")
df2 <- data.frame(cluster=2,tsfunc(20))
names(df2) <- c("cluster","id","x","y")
df3 <- data.frame(cluster=3,tsfunc(40))
names(df3) <- c("cluster","id","x","y")
df4 <- data.frame(cluster=4,tsfunc(80))
names(df4) <- c("cluster","id","x","y")
do.call("rbind", list(df1, df2, df3, df4))
I wonder if there is a way to use more concise code (eg, with sapply
or replicate
or map
)). Thanks!
You can use Map()
to iterate over your changing parameters
do.call("rbind", Map(function(x,y) {
data.frame(cluster=x, tsfunc(y))
}, 1:4, c(10,20,40,80)))
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.