On Apr 19, 2011, at 3:19 PM, Steven Wolf wrote:
I am trying to convert a string to a vector, and I'm stuck!
Suppose you have a string of numbers (string) that you want to
convert to a
vector (vec). I am able to split the string turning it into a list
by using
strsplit, but this makes a list, which I can't seem to access the
way that
I'd like to (it becomes a character list of only one(?!?) element.)
string<-"1,1,2,3,5,8"
list<-strsplit(string,",")
list # Produces this ugly output with the [[1]] crap which doesn't
let me
in!!!!!!!
It produces a list. To return an unlist-ed version, what else?
> unlist(list)
[1] "1" "1" "2" "3" "5" "8"
And to make it a numeric vector ... also simple:
> as.numeric(unlist(list))
[1] 1 1 2 3 5 8
> vec <- as.numeric(unlist(list))
> vec == c(1,1,2,3,5,8)
[1] TRUE TRUE TRUE TRUE TRUE TRUE
> all.equal(vec , c(1,1,2,3,5,8) ) # better practice with numeric
values
[1] TRUE
> identical(vec , c(1,1,2,3,5,8) )
# will not be true in all situations where newbs think it will be
[1] TRUE
--
David.
vec<-c(1,1,2,3,5,8) # All I really want in the end
(I'm reading each string from a .csv file using read.csv, so I can't
just
edit my way out of this as my csv file has 200 lines---and counting,
if
there is a more elegant way of doing this, let me know, my .csv file
has
other values in columns, and each string that I'm reading in has a
different
number of elements, so, for example, string2 might be "1,3,5,7,9" and
string3 might be "7". My bigger problem is that I probably am not
handling
the data.frame object properly. In other words, I might be so bass-
ackward
that I'm doomed to fail without handling the original read-in
properly. A
sample of my .csv file looks like this:
Rnum,Cnum,Pnums
1,1,"1,6,7,23,29,31,34,40,45"
1,2,"4,9,22,26,30,38,44,46,47"
1,3,"2,48"
1,4,"3,16,19,41"
1,5,"8,11,12,17,25"
)
Thanks,
Steven Wolf
[[alternative HTML version deleted]]
______________________________________________
R-help@r-project.org mailing list
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, MD
West Hartford, CT
______________________________________________
R-help@r-project.org mailing list
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.