开发者

R strsplit problem (easy fix?)

This should be an easy thing to do. The similar examples I have read on here have been a bit more complex and the techniques are not reall开发者_Go百科y working for me.

I have a variable called id_string

> typeof(id_string)
[1] "character"

and

> id_string
[1] "1,2,5,6,10"

What I want to do is split these values out and store them in a new variable. Such that, for example:

x[1] = 1
x[4] = 6
x[5] = 10

I tried to do

x <- strsplit(id_string,",") 

to split it by comma but I just get x = "1 2 5 6 10"

I read through this post on here which is similar and thought that something like

x <- read.csv(textConnection(id_string))

would work but to no avail.

Perhaps I am over thinking this. Please let me know if you have any ideas. Thank you.


Not sure what you're doing wrong because it works as advertised.

> x <- unlist(strsplit("1,2,5,6,10", ","))
> x
[1] "1"  "2"  "5"  "6"  "10"
> x[1]
[1] "1"

Keep in mind that strsplit returns a list.


Sticking with strsplit as outlined above is probably best.

I think read.csv wasn't doing what you expected because it was looking for a header. You could try:

s <- "1,2,5,6,10"
read.csv(textConnection(s), header=FALSE)

explicitly telling it not to look for a header. You'll still have to pull your numbers out of the resulting data.frame though. You might be better off going with the lower level function scan, which will give you the vector of numbers directly:

scan(textConnection(s), sep=",", quiet=TRUE)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜