Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (50.2k points)

In the following code I want to extract cont, p0 and pf variables from nested loop as 3 different vectors from this code.

v<-c("a","b","c","d","e","f","g","h")

n<-length(v)

mv<-5

a<-n-(mv-1)

cont<-0

for (num in (a-1):0){

  for (i in 0:num){

    cont<-cont+1

    p0<-v[a-num]

    pf<-v[n-i]

  }

}

My desired output should look like this:

> print(cont)

[1] 1 2 3 4 5 6 7 8 9 10

> print (p0)

[1] "a" "a" "a" "a" "b" "b" "b" "c" "c" "d"

> print (pf)

[1] "h" "g" "f" "e" "h" "g" "f" "h" "g" "h"

1 Answer

0 votes
by (108k points)

In R programming, you can have the cont as an index variable and can store the other variables in a form of vectors, refer the following.

v<-c("a","b","c","d","e","f","g","h")

n<-length(v)

mv<-5

a<-n-(mv-1)

cont = 0

cont_stored = vector();

p0 = vector();

pf = vector();

for (num in (a-1):0){

  for (i in 0:num){

    cont <- cont+1

    cat("cont = ", cont, "\n"); ## useful function for printing stuff out in loops

    cont_stored[cont] = cont;

    p0[cont] = v[a-num]

    pf[cont] = v[n-i]

  }

}

cont_stored

p0

pf

Related questions

Browse Categories

...