Ihda
Ihda

Reputation: 111

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

I have a character vector like this:

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

And I want to split character vector into list based on length of a 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'm trying to use sapply(split.char, length) for defining length of list split.char

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

But I didn't get the desired output and I constantly get this warnings message:

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

Upvotes: 3

Views: 121

Answers (2)

akrun
akrun

Reputation: 887118

You could use relist which will give similar structure for 'a' as the 'split.char' (including the 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"  

Upvotes: 3

sgibb
sgibb

Reputation: 25736

You could try the following:

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

f has to be of the same length as x (if it is of length one or a divider of x it would be recycled).

Upvotes: 4

Related Questions