Reputation: 5446
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?
Upvotes: 1
Views: 1400
Reputation: 263301
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
Upvotes: 5