简体   繁体   中英

converting a string from csv to a vector of numbers in R

I have the following instruction in R:

y <- rep(1:2,each=3)

which I know that it generates a vector of 1 and 2:

[1] 1 1 1 2 2 2

How I can get the same results if I want to extract that information from a csv line that has the form:

[1] ",,1,1,1,2,2,2"

I have tried with as.numeric and is.na and I still get an empty list. Any help?

MatthewPlourde suggestion incorported:

> txt <- ",,1,1,1,2,2,2"
> scan(text=txt,, sep=",")
Read 8 items
[1] NA NA  1  1  1  2  2  2

Other option would be strsplit.

> unlist( strsplit(txt, ",") )
[1] ""  ""  "1" "1" "1" "2" "2" "2"

With adoption of Matthew's suggestion there is not a need to answer the question "how to convert to numeric?" .... but if you had a character vector it would have been ... now that you have separated into components, use as.numeric :

> as.numeric( scan(textConnection(txt), what="", sep=",") )
Read 8 items
[1] NA NA  1  1  1  2  2  2

Another option would be to read with scan using the numeric format:

> scan(textConnection(txt), what=numeric(0), sep=",")
Read 8 items
[1] NA NA  1  1  1  2  2  2

And to remove the NAs:

> numbas <- scan(textConnection(txt), what=numeric(0), sep=",")
Read 8 items
> numbas[!is.na(numbas)]
[1] 1 1 1 2 2 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM