Home > Software design >  How to sequence all numeric elements in R?
How to sequence all numeric elements in R?

Time:10-26

I would like to sequence a random vector:

<v1 <- apply(combn(1:8,2),2,paste0,collapse="")>
<v2 <- apply(combn(8:1,2),2,paste0,collapse="")>
<v <- c(v1,v2)>

Then I got a vector like this:

[1] 12 13 14 15 16 17 18 23 24 25 26 27 28 34 35 36 37 38 45 46 47 48 56 57 58 67 68 78
[29] 87 86 85 84 83 82 81 76 75 74 73 72 71 65 64 63 62 61 54 53 52 51 43 42 41 32 31 21

However, I want to sequence this vector from small to large number like:

12, 13, 14, 15, 16, 17, 18, 21, 23, 24, 25 .... (11/22/33/44/55/66/77/88 should not be included)

Thank you for your help!

CodePudding user response:

Convert to numeric and then sort:

sort(as.numeric(v))

 [1] 12 13 14 15 16 17 18 21 23 24 25 26 27 28 31 32 34 35 36 37 38 41 42 43
[25] 45 46 47 48 51 52 53 54 56 57 58 61 62 63 64 65 67 68 71 72 73 74 75 76
[49] 78 81 82 83 84 85 86 87

There are shorter way to do this though:

x <- seq(11, 18)   rep(seq(0, 70, 10), each = 8)
x[x %% 11 != 0]

Or even shorter:

x <- c(outer(1:8, (1:8)*10, ` `))
x[x %% 11 != 0]

 [1] 12 13 14 15 16 17 18 21 23 24 25 26 27 28 31 32 34 35 36 37 38 41 42 43
[25] 45 46 47 48 51 52 53 54 56 57 58 61 62 63 64 65 67 68 71 72 73 74 75 76
[49] 78 81 82 83 84 85 86 87

CodePudding user response:

You can sort(v) or do the whole thing in one line, like this:

sort(combn(1:8, 2, \(x) c(paste(x,collapse=""),paste(rev(x), collapse=""))))

Output:

 [1] "12" "13" "14" "15" "16" "17" "18" "21" "23" "24" "25" "26" "27" "28" "31" "32" "34" "35" "36" "37" "38"
[22] "41" "42" "43" "45" "46" "47" "48" "51" "52" "53" "54" "56" "57" "58" "61" "62" "63" "64" "65" "67" "68"
[43] "71" "72" "73" "74" "75" "76" "78" "81" "82" "83" "84" "85" "86" "87"

Of course, you can always just do this:

(11:88)[(11:88)%!=0]
  • Related