[R] Changing names of a string variable

David Winsemius dwinsemius at comcast.net
Tue Dec 7 20:36:34 CET 2010


On Dec 7, 2010, at 2:31 PM, Erik Iverson wrote:

> Hello,
>
> To do what you want, see ?toupper :
>
> levels(dat$target) <- toupper(levels(dat$target))
>
> However, for clarity,
>
> dat$target is not a "string variable", it is a factor,
> which you can verify with
>
> > str(dat)

And to further clarify, it is a factor because of the default behavior  
of read.table and data.frame in creating factors when offered streams  
of character data. The stringsAsFactors=FALSE argument can be used  
within these functions or can be set globally with options().

-- 
David.

>
> Factors are enumerated types, and have a discrete
> set of 'levels' associated with them,
> which can be queried with the ?levels function.
>
> 'Behind the scenes', R is storing this variable
> as numeric codes, not the character string associated
> with each numeric code.
>
> This contrasts with character vectors.
>
>
> --Erik
>
> Jahan wrote:
>> Hello,
>> Here is the data set I am working with:
>> dat=read.csv('http://dl.dropbox.com/u/1852742/relexpressions.csv')
>> names(dat)
>> #Under the 'target' column, I want to change all of the values into
>> all capital letters (e.g. fgf2 becomes FGF2).  I have taken a loop
>> approach but I think my Python background is confusing me.  Here is
>> what I attempted:
>> for(line in dat[,1]){if(line=='fgf2'){line<-'FGF2'}}
>> #I made sure that it was looping through each line by entering:
>> for(line in dat[,1]){if(line=='fgf2'){print(line)}} #Which did  
>> exactly
>> what I thought it would.
>> #This doesn't change anything, though.  Also, after reading the
>> documentation I am still confused how to add multiple "if"
>> statements.  I would need that because I need to change the names of
>> fgf2, fgf7, and fgf10.
>> #I am sure there is a built-in function to do what I need, but I
>> haven't found it yet so I tried this loop method.  Any help is  
>> greatly
>> appreciated!
>> Jahan


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list