简体   繁体   中英

R - how to combine vectors from loop output

I have created a function lpnorm which returns a single value 'x' for every input.

for (t in 1:6){
    M= data[t:(t+3), ]
    lpnorm(M)
    }

when i loop the function it produces the correct output, however the vectors all appear to be independent

[1] 0.0003370998
[1] 0.0003379513
[1] 0.0002855089
[1] 0.0003535439
[1] 0.0003683093
[1] 0.0003443804

Therefore when i try to plot the data:

for (t in 1:6){
    M= data[t:(t+3), ]
    plot(t, lpnorm(M))
    }

They all appear on separate diagrams

With out a reproducible example you could do the following:

res <- matrix(NA, nrow=6, ncol=2) ##intitialize a matrix to store the results
for (t in 1:6){
    M <- data[t:(t+3), ]
    res[t, ] <- c(t, lpnorm(M)) #for each value of t we save the results in the res matrix
    }

plot(res[,1], res[, 2])

The reason you are getting a plot for each value of lpnorm(M) is because you are not saving the result of each iteration.

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