I want to produce a list of unequal vectors, that represent the integers between the n th values of two existing vectors, n and L.
Example
> n
[1] 1 2 3 4 5 6 7
> L
[1] 2 2 4 4 4 4 4
For each value of n, I want to concatenate the integers between L and n when n>L, or retrieve the single value of n when L=n, or replace with value of 0 when L>n. I want to get a list (or other entity) with unequal vectors. Ideal output:
i
1 0
2 2
3 0
4 4
5 4 5
6 4 5 6
7 4 5 6 7
I have tried to use the colon operator (with the intention of replacing negative values later), eg
c((L):n)
But it comes with the error:
numerical expression has 205 elements: only the first used
We can use Map
f1 <- function(x,y) c(x, if(x < y) 0 else if(x == y) x else y:x)
Map(f1, n, L)
#[[1]]
#[1] 1 0
#[[2]]
#[1] 2 2
#[[3]]
#[1] 3 0
#[[4]]
#[1] 4 4
#[[5]]
#[1] 5 4 5
#[[6]]
#[1] 6 4 5 6
#[[7]]
#[1] 7 4 5 6 7
If we need a vector
sapply(Map(f1, n, L), paste, collapse=" ")
#[1] "1 0" "2 2" "3 0" "4 4" "5 4 5" "6 4 5 6" "7 4 5 6 7"
Or if we just want to print it
for(i in seq_along(n))
cat(c(n[i], if(n[i] < L[i]) 0 else if(n[i] == L[i]) n[i] else L[i]:n[i]), "\n")
#1 0
#2 2
#3 0
#4 4
#5 4 5
#6 4 5 6
#7 4 5 6 7
A method using Reduce
with accumulate = TRUE
argument, giving a vector as a result
v1 <- ifelse(L > n, 0, ifelse(n == L, L, -1))
v1[v1 == -1] <- unique(unlist(Reduce(paste, x[v1==-1], y[v1==-1], accumulate = TRUE)))[-1]
#[1] "0" "2" "0" "4" "4 5" "4 5 6" "4 5 6 7"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.