Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 20 / 68

Splitting and joining strings (strsplit and paste)

This lesson covers splitting and joining strings with R's strsplit and paste, with the aim of handling CSV-style data.

strsplit() splits a string into a list. Conversely, paste() gathers a vector into a single string. Both come up constantly when working with CSV-style data.

The sample code splits a comma-separated string into a vector with strsplit(csv, ",")[[1]] and rebuilds it as a slash-separated string with paste(fruits, collapse = " / "). Note the [[1]], which takes the first element (the vector) out of the list.

A common early stumble is that strsplit() returns a list. If you expect a plain vector and forget the [[1]], you end up handling a list and get surprising behaviour.

In professional work, this is a standard pairing that shows up whenever CSV files are read or logs are parsed.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)