# You should not use split in production code

**R snippets**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Recently I have stumbled on a problem with split function applied on list of factors. The issue is that it might produce wrong splits when splitting factors contain dots.

Here is the example of the problem. Invoking the following code:

**<-**data.frame

**(**x

**=**rep

**(**c

**(**“a”, “a.b”

**)**, 3

**)**,

**=**rep

**(**c

**(**“b.c”, “c”

**)**, 3

**)**,

**=**1

**:**6

**)**

**(**df, df

**[**,

**–**3

**])**

produces:

And we can see that incorrect splits were produced. The issue is that split uses interaction to combine list of factors passed to it. One can see this problem by invoking:

**(**df

**[**,

**–**3

**])**

The problem might be not a huge issue in interactive mode, but in production code such behavior is a problem. There are three obvious ways to improve how split works:

- Rewriting split internals to avoid this problem;
- Allow passing sep parameter to split that would be further passed to interaction;
- Warning if resulting number of levels in combined factor does not equal the multiplication of number of levels of combined factors (assuming drop = F option).

Until this issue is solved there is a workaround using split and two other options using by and dlply (from plyr package):

**(**df, lapply

**(**df

**[**,

**–**3

**]**, as.integer

**))**

**(**df, df

**[**,

**–**3

**]**, identity

**)**

**(**plyr

**)**

**(**df,.

**(**x,y

**))**

**leave a comment**for the author, please follow the link and comment on their blog:

**R snippets**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.