How to split a character vector based on the length of the list

I have a character vector like:

a<-c("tanaman","cabai","banget","hama","sakit","tanaman","koramil","nogosari",
    "melaks","ecek","hama","tanaman","padi","ppl","ds","rambun") 

      

And I want to split a character vector into a list based on the length of the list like below:

split.char<-list(c("tanaman", "cabai"),c("banget", "hama", 
"penyakit", "tanaman"),c("koramil", "nogosari", "melaks", "pengecekan", "hama",
 "tanaman"  , "padi", "ppl", "ds", "rambun"))  

      

I am trying to use sapply(split.char, length)

to determine the length of a listsplit.char

Length <- sapply(split.char, length)
for(i in Length){
  split(a, Length(i))
 } 

      

But I didn't get the desired result and I keep getting this warning:

1: In split.default(ok, Length) : data length is not a multiple of split variable
2: In split.default(ok, Length) : data length is not a multiple of split variable
3: In split.default(ok, Length) : data length is not a multiple of split variable

      

+3


source to share


2 answers


You can try this:

split(x=a, f=rep(seq_along(Length), Length))

      



f

must have the same length as x

(if it has length 1 or divisor x

, it will be reworked).

+4


source


You can use relist

which will give a similar structure for "a" as "split.char" (including length

)



relist(a, skeleton=split.char)
#[[1]]
#[1] "tanaman" "cabai"  

#[[2]]
#[1] "banget"  "hama"    "sakit"   "tanaman"

#[[3]]
#[1] "koramil"  "nogosari" "melaks"   "ecek"     "hama"     "tanaman" 
#[7] "padi"     "ppl"      "ds"       "rambun"  

      

+3


source







All Articles