[R] two apparent anomalies

Sarah Goslee sarah.goslee at gmail.com
Sat Jan 22 15:47:07 CET 2011


(1)

> a <- c("a", "b")
> str(a)
 chr [1:2] "a" "b"
> b <- c(1,2)
> str(b)
 num [1:2] 1 2
> c <- data.frame(a, b)
> str(c)
'data.frame':	2 obs. of  2 variables:
 $ a: Factor w/ 2 levels "a","b": 1 2
 $ b: num  1 2
> mode(c$a)
[1] "numeric"
> c2 <- data.frame(a, b, stringsAsFactors=FALSE)
> str(c2)
'data.frame':	2 obs. of  2 variables:
 $ a: chr  "a" "b"
 $ b: num  1 2
> mode(c2$a)
[1] "character"


(2)
> a <- c("a", "a", "b", "b", "c")
> levels(as.factor(a))
[1] "a" "b" "c"
> b <- a[1:3]
> b
[1] "a" "a" "b"
> levels(as.factor(b))
[1] "a" "b"
> a <- as.factor(a)
> a
[1] a a b b c
Levels: a b c
> a[1:3]
[1] a a b
Levels: a b c


On Sat, Jan 22, 2011 at 9:16 AM, analyst41 at hotmail.com
<analyst41 at hotmail.com> wrote:
> (1)
>
>> a = c("a","b")
>> mode(a)
> [1] "character"
>> b = c(1,2)
>> mode(b)
> [1] "numeric"
>> c = data.frame(a,b)
>> mode(c$a)
> [1] "numeric"
>
> (2)
>
>
>> a = c("a","a","b","b","c")
>> levels(as.factor(a))
> [1] "a" "b" "c"
>> levels(as.factor(a[1:3]))
> [1] "a" "b"
>> a = as.factor(a)
>> levels(a)
> [1] "a" "b" "c"
>> levels(a[1:3])
> [1] "a" "b" "c"
>
> Any explanation would be helpful.  Thanks.
>
-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list