Re: [R] Assign Character Value to Data Frame

From: Joshua Wiley <jwiley.psych_at_gmail.com>
Date: Tue, 12 Apr 2011 11:31:28 -0700

Hi John,

The error arises because the "hold" data frame contains factors. This happens by default when creating data frames with character data as you did. Factors have a set number of levels and new values cannot be assigned to them that fall outside their specified levels, hence the error. The solution is to create all the columns in the dat frame as character to begin with or transform them to that (or at least ensure they are not factors). For example:

> hold <- data.frame(symbol = character(1), stringsAsFactors = FALSE)
> hold[1, ] <- "NYSE:MMM"
> hold

    symbol
1 NYSE:MMM See ?data.frame for details.

Hope this helps,

Josh

On Tue, Apr 12, 2011 at 11:20 AM, Sparks, John James <jspark4_at_uic.edu> wrote:
> Dear R Helpers,
>
> I am trying to write a character value to the row of a data frame and am
> running into a problem that I don't have when I do this for numeric
> arguments.  For example, the following works just fine:
>
>> test<-data.frame(number=numeric(1))
>> test[1,]<-.5
>> test
>  number
> 1    0.5
>
> But the following bombs out:
>
>> hold<-data.frame(symbol=character(1))
>> hold[1,]<-"NYSE:MMM"
> Warning message:
> In `[<-.factor`(`*tmp*`, iseq, value = "NYSE:MMM") :
>  invalid factor level, NAs generated
>
> Could someone please guide me as to what adjustment I need to make to
> assign this character value to this row of the data frame?  Your help
> would be very much appreciated.
>
> --John Sparks
>
> ______________________________________________
> R-help_at_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.
>

-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/

______________________________________________
R-help_at_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.
Received on Tue 12 Apr 2011 - 18:34:32 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 12 Apr 2011 - 19:30:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive