abbas786
abbas786

Reputation: 401

Increment every nth range R

I am writing R code where there's a vector 'x' which contains values 1 to 100 and I want to create another vector 'y' which subsets a range of values at every nth range. I'm sure I can use the rep() and seq() but I can't figure out the code to get what I need. Here's what the output should look like

x <- 1:100

y <- 1 2 3 11 12 13 21 22 23 31 32 33 41 42 43 51 52 53 61 62 63 71 72 73 81 82 83 91 92 93

So if I was to do have a vector x <- 1001:1100, x[y] should return:

  1001 1002 1003 1011 1012 1013 1021 1022 1023 1031 1032 1033 1041 1042 1043...etc

Any ideas?

Upvotes: 2

Views: 707

Answers (4)

smoe
smoe

Reputation: 630

Hm. This started out as fun, but now I happen to like it since it is constructed in basically the same way the author of the question put it:

> do.call("c",lapply(0:5,function(X) 1:3+10*X))
 [1]  1  2  3 11 12 13 21 22 23 31 32 33 41 42 43 51 52 53

Upvotes: 0

talat
talat

Reputation: 70316

You could use grepl for that:

x <- 1001:1100
y <- grepl("[1-3]$", x)
x[y]
# [1] 1001 1002 1003 1011 1012 1013 1021 1022 1023 1031 1032 1033 1041 1042 1043 1051 1052
#[18] 1053 1061 1062 1063 1071 1072 1073 1081 1082 1083 1091 1092 1093

It simply checks for each element of x whether the last digit is in the range of 1, 2 or 3 and if so, it returns TRUE, otherwise FALSE. This logical index is then used to subset x.


In case your objective is not to subset elements ending in 1,2 or 3 but instead, to always subset 3 elements, then leave out 7, and then subset 3 again etc... you could do:

x <- 1001:1100
y <- rep(c(TRUE, FALSE), c(3, 7))
x[y]
# [1] 1001 1002 1003 1011 1012 1013 1021 1022 1023 1031 1032 1033 1041 1042 1043 1051 1052
#[18] 1053 1061 1062 1063 1071 1072 1073 1081 1082 1083 1091 1092 1093

In this case, vector y which is again logical, is recycled - note that length(x) should be divisible by length(y) for this to work properly.

Upvotes: 5

Denis Rasulev
Denis Rasulev

Reputation: 4069

Probably this may help you:

x <- 1:100
y <- as.integer()
for(i in seq(1, length(x), 10)) {
    y <- append(y, c(x[i], x[i+1], x[i+2]))
}

Upvotes: 1

user3710546
user3710546

Reputation:

For fun, With outer:

x <- 1001:1100
y <- as.vector(outer(1:3, seq(0, length(x)-10, 10), "+"))
x[y]
#  [1] 1001 1002 1003 1011 1012 1013 1021 1022 1023 1031 1032 1033 1041 1042 1043
# [16] 1051 1052 1053 1061 1062 1063 1071 1072 1073 1081 1082 1083 1091 1092 1093

Upvotes: 1

Related Questions