简体   繁体   中英

Splitting a vector for variable no. of times into nested vectors

I have a vector, say f1 .

f1 = c(1, 0,  0,  1,  0,  1,  1,  1,  0,  1, -6)

I want to split this vector into a nested list of lists as follows, based on the location of 1's in the original list. The R code for the same is as follows:

dfg <- function(f1) {
  df<-which(f1 %in% 1)
  m<-c()
  for(i in 1:df[2]-1) {
    m<-c(m,list(f1[i]))
  }
  m<-c(m,list(f1[df[2]:length(f1)]))
  return(m)
}

This gives the output as follows:

[[1]]
numeric(0)

[[2]]
[1] 1

[[3]]
[1] 0

[[4]]
[1] 0

[[5]]
[1]  1  0  1  1  1  0  1 -6

So far so good. Now note that m[[5]] has length > 1.

I want to repeat this procedure above till the length of every element at every level of nesting in the output is 1.

How to ensure that the R function listed above gets executed for arbitrary levels of nesting?

EDIT: As requested in the comments, I'm giving the desired end result for the whole thing as follows.

[[1]] numeric(0)

[[2]] [1] 1

[[3]] [1] 0

[[4]] [1] 0

[[5]]

[[5]][[1]] numeric(0)

[[5]][[2]] [1] 1

[[5]][[3]] [1] 0

[[5]][[4]]

[[5]][[4]][[1]] numeric(0)

[[5]][[4]][[2]] [1] 1

[[5]][[4]][[3]]

[[5]][[4]][[3]][[1]] numeric(0)

[[5]][[4]][[3]][[2]] [1] 1

[[5]][[4]][[3]][[3]]

[[5]][[4]][[3]][[3]][[1]] numeric(0)

[[5]][[4]][[3]][[3]][[2]] [1] 1

[[5]][[4]][[3]][[3]][[3]] [1] 0

[[5]][[4]][[3]][[3]][[4]] [1] 1 -6

(I know the final element has length 2, not 1. But that is not a problem for me. I shall sort it out in the function dfg itself.)

Though it's a bit mysterious to me why you would want this nested structure, the most natural way I could think of to construct it would be with a recursive function:

f1 = c(1, 0,  0,  1,  0,  1,  1,  1,  0,  1, -6)
dfg <- function(f1) {
  df <- which(f1 == 1)
  if (length(df) <= 1) f1
  else c(list(numeric(0)), as.list(f1[1:(df[2]-1)]), list(dfg(f1[df[2]:length(f1)])))
}

dfg(f1)
# [[1]]
# numeric(0)
# 
# [[2]]
# [1] 1
# 
# [[3]]
# [1] 0
# 
# [[4]]
# [1] 0
# 
# [[5]]
# [[5]][[1]]
# numeric(0)
# 
# [[5]][[2]]
# [1] 1
# 
# [[5]][[3]]
# [1] 0
# 
# [[5]][[4]]
# [[5]][[4]][[1]]
# numeric(0)
# 
# [[5]][[4]][[2]]
# [1] 1
# 
# [[5]][[4]][[3]]
# [[5]][[4]][[3]][[1]]
# numeric(0)
# 
# [[5]][[4]][[3]][[2]]
# [1] 1
# 
# [[5]][[4]][[3]][[3]]
# [[5]][[4]][[3]][[3]][[1]]
# numeric(0)
# 
# [[5]][[4]][[3]][[3]][[2]]
# [1] 1
# 
# [[5]][[4]][[3]][[3]][[3]]
# [1] 0
# 
# [[5]][[4]][[3]][[3]][[4]]
# [1]  1 -6

Note that I took advantage of the fact that as.list(1:3) is equivalent to list(1, 2, 3) to simplify the construction of the list in dfg .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM