Split delimited single value character vector
Asked Answered
G

2

7

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.

Gynaecocracy answered 13/10, 2015 at 12:7 Comment(0)
P
8

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.

Pastelist answered 13/10, 2015 at 12:13 Comment(2)
It returns a list in case wkdays is a vector of length>1 and several splits are needed. Here wkdays is a vector of length 1 so you would extract the first element of the list with strsplit(wkdays, ",")[[1]].Llanes
@antoine-sac true, added unlistPastelist
U
3

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

Udine answered 25/3, 2023 at 19:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.