Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating elements in a vector with a for loop

I want to make a vector from 3:50 in R, looking like

3 4 4 5 6 6 7 8 8 .. 50 50

I want to use a for loop in a for loop but it's not doing wat I want.

f <- c()
for (i in 3:50) {
  for(j in 1:2) {
    f = c(f, i)
  }
}

What is wrong with it?

like image 258
Max Avatar asked Feb 17 '18 10:02

Max


People also ask

How do you stop a loop from repeating?

The only way to exit a repeat loop is to call break.

How do you repeat an element in Matlab?

u = repelem( v , n ) , where v is a scalar or vector, returns a vector of repeated elements of v . If n is a scalar, then each element of v is repeated n times. The length of u is length(v)*n . If n is a vector, then it must be the same length as v .


1 Answers

Use the rep function, along with the possibility to use recycling logical indexing ...[c(TRUE, FALSE, TRUE, TRUE)]

rep(3:50, each = 2)[c(TRUE, FALSE, TRUE, TRUE)]

 ## [1]  3  4  4  5  6  6  7  8  8  9 10 10 11 12 12 13 14 14 15 16 16 17 18 18 19
## [26] 20 20 21 22 22 23 24 24 25 26 26 27 28 28 29 30 30 31 32 32 33 34 34 35 36
## [51] 36 37 38 38 39 40 40 41 42 42 43 44 44 45 46 46 47 48 48 49 50 50

If you use a logical vector (TRUE/FALSE) as index (inside [ ]), a TRUE leads to selection of the corresponding element and a FALSE leads to omission. If the logical index vector (c(TRUE, FALSE, TRUE, TRUE)) is shorter than the indexed vector (rep(3:50, each = 2) in your case), the index vector is recyled.

Also a side note: Whenever you use R code like

 x = c(x, something)

or

 x = rbind(x, something)

or similar, you are adopting a C-like programming style in R. This makes your code unnessecarily complex and might lead to low performance and out-of-memory issues if you work with large (say, 200MB+) data sets. R is designed to spare you those low-level tinkering with data structures.

Read for more information about the gluttons and their punishment in the R Inferno, Circle 2: Growing Objects.

like image 93
akraf Avatar answered Oct 06 '22 09:10

akraf