Subset Vector: How to programmatically pass a negative index safely?

For a vector, let's say v = 1:10you can remove elements from vusing negative indexing, for example. v[-1], v[-length(v)], v[-c(2,3)]To remove the first, the last and second / third elements respectively.

I would like to split vby going to the split index n, taking values ​​from 0 to length(v). Code below:

v1 <- v[1:n]
v2 <- v[-c(1:n)]

except works fine n = 0. Now I know that it is 1:nusually unsafe and should be replaced with seq_len(n), however, assignment v2 <- v[-seq_len(0)]creates an empty vector.

Is there a way to make this “safe” using parenthesis notation? Otherwise, I know how to do this using head and tails:

v1 <- head(v, n)
v2 <- tail(v, length(v) - n)

Corresponding to another q / as:

Addition to an empty index vector - empty pointer vector

+4
source share
2 answers

You can use the operator if()inside brackets. For example, this will simply return the entire vector if it nis zero and delete the sequence 1:notherwise.

x <- 1:10

n <- 0
x[ if(n == 0) TRUE else -seq_len(n) ]  ## n == 0 is !n for the golfers
# [1]  1  2  3  4  5  6  7  8  9 10

n <- 5
x[ if(n == 0) TRUE else -seq_len(n) ]
# [1]  6  7  8  9 10
+4
source
v = 1:10
n = 0; split(v, seq_along(v)/min(n,length(v)) <= 1)
#$`FALSE`
# [1]  1  2  3  4  5  6  7  8  9 10

n = 1; split(v, seq_along(v)/min(n,length(v)) <= 1)
#$`FALSE`
#[1]  2  3  4  5  6  7  8  9 10

#$`TRUE`
#[1] 1

n = 10; split(v, seq_along(v)/min(n,length(v)) <= 1)
#$`TRUE`
# [1]  1  2  3  4  5  6  7  8  9 10

n = -10; split(v, seq_along(v)/min(n,length(v)) <= 1)
#$`TRUE`
# [1]  1  2  3  4  5  6  7  8  9 10

n = 100; split(v, seq_along(v)/min(n,length(v)) <= 1)
#$`TRUE`
# [1]  1  2  3  4  5  6  7  8  9 10

Further simplified by thelatemail in comment

split(v, seq_along(v) > n)
+4
source

Source: https://habr.com/ru/post/1671546/


All Articles