[R] ifelse function

Steven McKinney smckinney at bccrc.ca
Wed Nov 28 05:03:28 CET 2007


Hi Min,

You don't need to loop.
Since your column "g" is a factor variable,
it already has integer values 'under the covers'.

> pth <- data.frame(g = c("sh","ao","ao","sh","iy","dcl","dcl","aa","iy","iy","aa","sh","ao","ao"))
> 
> pth
     g
1   sh
2   ao
3   ao
4   sh
5   iy
6  dcl
7  dcl
8   aa
9   iy
10  iy
11  aa
12  sh
13  ao
14  ao
> class(pth$g)
[1] "factor"

You can get the factor integer values in a couple of ways:
e.g.

> pth$gn <- as.integer(pth$g)
> pth$gn
 [1] 5 2 2 5 4 3 3 1 4 4 1 5 2 2


See help("factor") for some discussion of factor
variables and their components.

Another way:

> unclass(pth$g)
 [1] 5 2 2 5 4 3 3 1 4 4 1 5 2 2
attr(,"levels")
[1] "aa"  "ao"  "dcl" "iy"  "sh" 
> 


Hope this helps


Best

Steven McKinney




-----Original Message-----
From: r-help-bounces at r-project.org on behalf of Min (Tilda) Zhang
Sent: Tue 11/27/2007 7:45 PM
To: r-help at r-project.org
Subject: [R] ifelse function
 
Hi there,

I need help with IFELSE function.

The column g of my dataset pth, pth$g consists of "aa", "ao", "dcl", "iy",
"sh".

The last few values of pth$g looks like:
[4496] sh  ao  ao  sh  iy  dcl dcl aa  iy  iy  aa  sh  ao  ao
Levels: aa ao dcl iy sh

I want to convert these values into 1,2,3,4,5. I tried to use a loop and I
found the following statement did not work.
> pth$g[1]<-ifelse(pth$g[1]=="aa",1,pth$g[1])
Warning message:
invalid factor level, NAs generated in: `[<-.factor`(`*tmp*`, 1, value = 5L)

Then I tried this statement. It works, but I do not understand how it
convert the values not only into 1 but also into 2,3,4,5 at the same time.

> pth$g<-ifelse(pth$g=="aa",1,pth$g)
> pth$g
   [1] 4  4  3  3  1  4  1  5 ....

I appreciate your help.

Min (Tilda) Zhang

Department of Statistics
North Carolina State University

______________________________________________
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.



More information about the R-help mailing list