Day 04 – little helper evenstrings

We at STATWORX work a lot with R and we often use the same little helper functions within our projects. These functions ease our daily work life by reducing repetitive code parts or by creating overviews of our projects. At first, there was no plan to make a package, but soon I realised, that it will be much easier to share and improve those functions, if they are within a package. Up till the 24th December I will present one function each day from helfRlein. So, on the 4th day of Christmas my true love gave to me…

What can it do?

This little helper splits a given string into smaller parts with a fixed length. But why? Well I needed this function whilst creating a plot with a long title. The text was too long for one line and instead of just cutting it or let it run over the edges, I wanted to separate it nicely.

How to use it?

Given a long string like

1
2
long_title <- c("Contains the months: January, February, March, April, May, June, July, August, September, October, November, December")

We want to split it after split = "," with a maximum length of char = 60.

1
2
short_title <- evenstrings(long_title, split = ",", char = 60)

The function has two possible output formats, which can be chosen by setting newlines = TRUE or FALSE:

  • one string with line separators \n

  • a vector with each sub part.

An other use case could be a message that is printed at the console with cat():

1
2
cat(long_title)

1
2
Contains the months: January, February, March, April, May, June, July, August, September, October, November, December

1
2
cat(short_title)

1
2
3
Contains the months: January, February, March, April, May,
 June, July, August, September, October, November, December

Code for plot example

1
2
3
4
5
6
7
8
9
10
11
12
p1 <- ggplot(data.frame(x = 1:10, y = 1:10),
 aes(x = x, y = y)) +
 geom_point() +
 ggtitle(long_title)

p2 <- ggplot(data.frame(x = 1:10, y = 1:10),
 aes(x = x, y = y)) +
 geom_point() +
 ggtitle(short_title)

multiplot(p1, p2)

Overview

To see all the other functions you can either check out our GitHub or you can read about them here.

Have a merry advent season!

Über den Autor

Jakob Gepp

Numbers were always my passion and as a data scientist and statistician at STATWORX I can fullfill my nerdy needs. Also I am responsable for our blog. So if you have any questions or suggestions, just send me an email!


STATWORXis a consulting company for data science, statistics, machine learning and artificial intelligence located in Frankfurt, Zurich and Vienna. Sign up for our NEWSLETTER and receive reads and treats from the world of data science and AI. 

**