From hpages at fhcrc.org  Tue Mar 27 19:23:55 2007
From: hpages at fhcrc.org (Herve Pages)
Date: Tue, 27 Mar 2007 10:23:55 -0700
Subject: [Rd] Unexpected result of as.character() and unlist() applied
 to a data frame
In-Reply-To: <39B6DDB9048D0F4DAD42CB26AAFF0AFA03EB2FBB@usctmx1106.merck.com>
References: <1174967313.460894116113f@webmail.fhcrc.org>
	<39B6DDB9048D0F4DAD42CB26AAFF0AFA03EB2FBB@usctmx1106.merck.com>
Message-ID: <4609532B.5050506@fhcrc.org>

Liaw, Andy wrote:
> Given that the behavior is exactly as I expected it be, I would call
> that "feature" (and IMHO not a very special one).  The two data frames
> are just different (try str() on them:  A in dd is factor, while A in
> dd2 is character), so I don't know why you'd expect unlist() on them to
> give you the same answer.

Not sure what I would expect for unlist(). I was just curious and decided
to try unlist() on a data frame and found this funny behaviour.

But for as.character(), I definetly wouldn't expect this:
  > as.character(dd)
  [1] "c(2, 3, 1)" "c(3, 2, 1)"
  > as.character(dd$A)
  [1] "b" "c" "a"

And generally speaking, it's a bad idea to have the semantic of standard objects
controlled by some obscure global option.  Here 2 people with a different
"stringsAsFactors" option will not get the same results when manipulating 'dd'.
It makes writing reproducible code harder because then you must remember to specify
the stringsAsFactors option everytime you create a data frame.

Cheers,
H.


> 
> Andy
> 
> From: hpages at fhcrc.org
>> Hi,
>>
>>> dd <- data.frame(A=c("b","c","a"), B=3:1) dd
>>   A B
>> 1 b 3
>> 2 c 2
>> 3 a 1
>>> unlist(dd)
>> A1 A2 A3 B1 B2 B3
>>  2  3  1  3  2  1
>>
>> Someone else might get something different. It all depends on 
>> the values of its 'stringsAsFactors' option:
>>
>>> dd2 <- data.frame(A=c("b","c","a"), B=3:1, stringsAsFactors=FALSE)
>>> dd2
>>   A B
>> 1 b 3
>> 2 c 2
>> 3 a 1
>>> unlist(dd2)
>>  A1  A2  A3  B1  B2  B3
>> "b" "c" "a" "3" "2" "1"
>>
>> Same thing with as.character:
>>
>>> as.character(dd)
>> [1] "c(2, 3, 1)" "c(3, 2, 1)"
>>> as.character(dd2)
>> [1] "c(\"b\", \"c\", \"a\")" "c(3, 2, 1)"
>>
>> Bug or "feature"?
>>
>> Note that as.character applied directly on dd$A doesn't have 
>> this "feature":
>>
>>> as.character(dd$A)
>> [1] "b" "c" "a"
>>> as.character(dd2$A)
>> [1] "b" "c" "a"
>>
>> Cheers,
>> H.
>>
>> ______________________________________________
>> R-devel at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-devel
>>
>>
>>
> 
> 
> ------------------------------------------------------------------------------
> Notice:  This e-mail message, together with any attachment...{{dropped}}



[Rd] Unexpected result of as.character() and unlist() applied to a data frame
Herve Pages