Split delimited single value character vector

2020-01-30 01:19发布

问题:

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.

回答1:

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.



标签: r vector