Skip to content

Assign Character Value to Data Frame

3 messages · Sparks, John, Joshua Wiley, Sarah Goslee

#
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:
number
1    0.5

But the following bombs out:
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
#
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:
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:

  
    
#
That column of your data frame contains a factor, rather than character
values. You don't tell us how you created the data frame, but you might
be interested in the stringsAsFactors option to data.frame() and read.table().

Or, if you do actually want a factor for that column, you can use factor()
to change the levels.

Sarah
On Tue, Apr 12, 2011 at 2:20 PM, Sparks, John James <jspark4 at uic.edu> wrote: