[R] Converting charter string to vector of numbers
David Winsemius
dwinsemius at comcast.net
Wed Mar 25 20:44:28 CET 2015
On Mar 25, 2015, at 10:27 AM, Turgidson wrote:
> Apologies for bringing up an old topic, but I am not finding working answers.
> I am also an R newbie, so I'm still on the steep part of the learning curve.
>
> I have a character string : "0.5 1 2 3 4"
>
> I need to convert it to a vector of numbers.
The releatively recent additon of teh text parameter to scan lets you do this:
scan(text="0.5 1 2 3 4" )
#Read 5 items
#[1] 0.5 1.0 2.0 3.0 4.0
And the values are of course assign()-able:
num <- scan(text="0.5 1 2 3 4")
#Read 5 items
num
#[1] 0.5 1.0 2.0 3.0 4.0
In the old days one needed to use textConnection() and one still needs to do so for readLines which does not use scan().
> I get as far as strsplit(),
> which gives me
>
> "0.5" "1" "2" "3" "4"
>
> this is still treated by R as a single item. I need to get it to look like
> this: "0.5", "1", "2", "3", "4"
>
> so that I can use as.numeric() and make it into a vector of numbers... I
> have been going mad because for text operations, commas and quotes are
> loaded with meaning, and I keep going around in circles.
>
> Any help would be appreciated
>
> Thanks
>
> Paul
>
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Converting-charter-string-to-vector-of-numbers-tp4705097.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
David Winsemius
Alameda, CA, USA
More information about the R-help
mailing list