简体   繁体   中英

How to extract specific element from vector using for loop in R

I have a vector and would like to extract a specific element of this vector using for loop function in R.

Here is my try:

par <- list(0.5,0.5)
par2 <- list(0,0.4)
Param <- c(par, par2)
s <- length(par)
m <- length(par2)
for(i in 1:2){
  par[[i]] <- Param[[i]]
  par2[[i]] <- Param[(length(par)+1):length(Param)]
}

I got this:

>

 par2
[[1]]
[[1]][[1]]
[1] 0

[[1]][[2]]
[1] 0.4


[[2]]
[[2]][[1]]
[1] 0

[[2]][[2]]
[1] 0.4


> par
[[1]]
[1] 0.5

[[2]]
[1] 0.5

the result of par is correct. However, par2 is wrong. It is repeated.

I would like to get this:

par[[1]] <- 0.5 , par[[2]] <- 0.5 , par2[[1]] <-0 and par2[[2]]<- 0.4 .

Any help, please?

It is because you index with a sequence both times in the loop

Param[(length(par)+1):length(Param)]

You can just use +i .

for(i in 1:2){
  par[[i]] <- Param[[i]]
  par2[[i]] <- Param[[length(par)+i]]
}

> par
[[1]]
[1] 0.5

[[2]]
[1] 0.5

> par2
[[1]]
[1] 0

[[2]]
[1] 0.4

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