[R] How do I extract single entries from a factor?

peter dalgaard pdalgd at gmail.com
Sat Nov 22 12:50:16 CET 2014


> On 22 Nov 2014, at 08:12 , Aditya Singh <aps6dl at yahoo.com> wrote:
> 
> Dear Boris and R-Experts,
> 
> I have a variable my_state which is a 2-letter character string telling which American state the user inputs. This I am do a if(identical(database entry,my_state)) to check for occurrences in the database.
> 
> The problem is that the database entry[i,j] shows as a factor with various levels, e.g. the output when I do class(database[i,j])is:
> 
> [1] "TX" 
> AL.. levels through WY
> 
> How do I convert a factor into a character?

How about as.character()? 

(Or, nip it in the bud using stringsAsFactors=FALSE when reading)

-pd


> 
> Aditya
> 
> 
> 
> On Saturday, November 22, 2014 12:40 AM, Boris Steipe <boris.steipe at utoronto.ca> wrote:
> Seems to me you probably wanted a "while" in line 4.
> 
> N.b.  There's also a missing "}" and totally messed up formatting :-(
> 
> B.
> 
> 
> 
> On Nov 21, 2014, at 1:19 PM, Aditya Singh <aps6dl at yahoo.com> wrote:
> 
>> 1 my_min= min(outcome_data[which(outcome_data$State==my_state),11],na.rm=TRUE) 
>> 2 print(my_min) 
>> 3 jkr=0 
>> 4 if (jkr<= 4706) {jkr=jkr+1 
>> 5 if (identical(outcome_data[jkr,11],my_min) && identical(outcome_data[jkr,7],my_state)) { 
>> 6 print((outcome_data[jkr,2])) 
>> 7 break 
>> 8 } 
>> 
>> 
>> Dear Experts,
>> 
>> My computer is never 'inside' of  the if condition at line 5, as jkr=0 always. my_min is a numeric. my_state is a 2 letter American State (character).
>> 
>> This code gives NULL as output. Wondering!
>> 
>> Its either very obvious or I am very dumb.
>> 
>> Please do do reply!
>> 
>> Aditya
>> 
>> ______________________________________________
>> 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.
> 
> ______________________________________________
> 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.
> 
> ______________________________________________
> 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.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list