sag
sag

Reputation: 5451

Split delimited single value character vector

I have a user provided String like "Mon,Tue,Wed,Thu,Fri". Please note that this value is user provided input. User may provide something like "Mon,Tue,Wed" and so on.

I want to get this as vector which will be used for plotting and for further analytics.

Since the value provided by user is a single comma delimited value, we need to separate the value in to individual values and then construct vector.

Is there any way to construct vector directly.

i.e I should get a vector from "Mon,Tue,Wed,Thu,Fri". As expected, below code returns a single value vector.

> weekdays <- c(days)

> print(weekdays)
[1] "Mon,Tue,Wed,Thu,Fri"

But I need something like below

> days <- c("Mon","Tue","Wed","Thu","Fri")
> print(days)
[1] "Mon" "Tue" "Wed" "Thu" "Fri"

Note that I am not reading a CSV file. I am just trying to read a user provided single CSV row as vector.

Upvotes: 7

Views: 1445

Answers (2)

Holger Brandl
Holger Brandl

Reputation: 11192

We can use stringr::str_split_1 (which is loaded automatically when using tidyverse):

library(stringr)
str_split_1("foo,bar", ",")
[1] "foo" "bar"

To me, this feels a bit more crisp compared to the accepted solution. See https://www.tidyverse.org/blog/2022/12/stringr-1-5-0/#splitting for details

Upvotes: 3

Jaap
Jaap

Reputation: 83215

You can use strsplit for that:

wkdays <- "Mon,Tue,Wed,Thu,Fri"
unlist(strsplit(wkdays, ","))

this gives:

> unlist(strsplit(wkdays, ","))
[1] "Mon" "Tue" "Wed" "Thu" "Fri"

An alternative is to use scan:

scan(text = wkdays, sep = ",", what = character())

which gives the same result.

Upvotes: 8

Related Questions