[R] why is this a factor?

Sarah Goslee sarah.goslee at gmail.com
Wed Aug 28 23:12:17 CEST 2013


Hi Ed,

Because that's the default for data.frame(), and a lot of people trip
over it just as you did. It's an easy fix:

R> data(iris)
R> iris <- data.frame(iris, annot=c(""), stringsAsFactors=FALSE)
R> iris[1,"annot"]<-"annotation"

Thanks for the very useful reproducible example.

Sarah

On Wed, Aug 28, 2013 at 4:56 PM, Ed Siefker <ebs15242 at gmail.com> wrote:
> I have a table, and I want a new column to add some annotations to.
> But it ends up as a factor instead of characters, and won't let me add
> arbitrary text.
>
>> data(iris)
>> iris<-data.frame(iris,annot=c(""))
>> iris[1,"annot"]<-"annotation"
> Warning message:
> In `[<-.factor`(`*tmp*`, iseq, value = "annotation") :
>   invalid factor level, NAs generated
>> class(iris[,"annot"])
> [1] "factor"
>> class(c(""))
> [1] "character"
>
> Why is c("") a character, but when I add it to a data frame it's a factor?
> What am I missing?  Is there a better way to add a new column to
> a data frame?
>


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list