[R] Converting 1-D array to vector

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Wed Aug 27 11:30:18 CEST 2008


N. Lapidus wrote:
> You were very close to an answer :
> as.vector(unlist(df[1,]))
>
>   
I'd use as.character() there, for clarity. It's not easy to remember
what as.vector on a factor variable does.

Also notice that the original post has serious confusion about what the
data structures are:

df is data frame, not a matrix
df[1,] is a one-row data frame, not a 1-d vector
the components of df are factors, not character vectors

A data frame is a kind of list, and lists are a kind of vector, hence
as.vector does nothing to df[,1]. The unlist() function applied to
factors will take the union of their level sets and concatenate the values.

An alternative way is to make sure that you have a character matrix to
begin with:

> as.matrix(df)
     x   y
[1,] "a" "d"
[2,] "b" "e"
[3,] "c" "f"
> as.matrix(df)[1,]
  x   y
"a" "d"

(but beware the rather surprising

> as.character(df)
[1] "1:3" "1:3"

!!!)

> Nael
>
> On Wed, Aug 27, 2008 at 7:53 AM, Ronnen Levinson <RML27 at cornell.edu> wrote:
>
>   
>>   Hi.
>>   How  do I convert a one-dimensional array of characters to a character
>>   vector? In the example below I am trying to get the result c("a","d").
>> The
>>   function as.vector() returns the same one-dimensional array, and unlist()
>>   returns something more complicated than I seek.
>>   Yours truly,
>>   Ronnen.
>>   P.S. E-mailed CCs of posted replies appreciated.
>>   > df=data.frame(x=letters[1:3],y=letters[4:6])
>>   > df
>>     x y
>>   1 a d
>>   2 b e
>>   3 c f
>>   > df[1,]
>>     x y
>>   1 a d
>>   > as.vector(df[1,])
>>     x y
>>   1 a d
>>   > unlist(df[1,])
>>   x y
>>   a d
>>   Levels: a b c d e f
>>   > c("a","d") # desired result
>>   [1] "a" "d"
>>     


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907



More information about the R-help mailing list