Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

How to use "for loop" to get couples of indexes every time in R?

Let's assume I have this vector v:


v = seq(1,30,1)

I write this simple loop:

for(i in v) {
  print(i)
}

However, I would like to write a loop that gives me, in time, 1:2, 3:4, 5:6, 7:8, etc. I would then get:

[1] 1,2
[1] 3,4
[1] 5,6
[1] 7,8
...

Can anyone help me?

Thanks!

question from:https://stackoverflow.com/questions/65951911/how-to-use-for-loop-to-get-couples-of-indexes-every-time-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe you can generate v with step of 2.

v = seq(1,30,2)
for(i in v) {
  cat(paste(i, i + 1, sep = ','), '
')
}

#1,2 
#3,4 
#5,6 
#7,8 
#9,10 
#11,12 
#13,14 
#...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...