Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split delimited single value character vector

Tags:

r

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.

like image 555
sag Avatar asked Oct 13 '15 12:10

sag


Video Answer


1 Answers

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.

like image 194
Jaap Avatar answered Sep 30 '22 03:09

Jaap