[R] Ifelse statement on a factor level data frame

Jim Lemon jim at bitwrit.com.au
Sun Sep 28 07:15:25 CEST 2014


On Sun, 28 Sep 2014 12:49:41 AM Kate Ignatius wrote:
> Quick question:
> 
> I am running the following code on some variables that are factors:
> 
> dbpmn$IID1new <- ifelse(as.character(dbpmn[,2]) ==
> as.character(dbpmn[,(21)]), dbpmn[,20], '')
> 
> Instead of returning some value it gives me this:
> 
> c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1))
> 
> Playing around with the code, gives me some kind of variation to it.
> Is there some way to get me what I want.  The variable that its
> suppose to give back is a bunch of sampleIDs.
> 
Hi Kate,
If I create a little example:

dbpmn<-data.frame(V1=factor(sample(LETTERS[1:4],20,TRUE)),
  V2=factor(sample(LETTERS[1:4],20,TRUE)),
  V3=factor(sample(LETTERS[1:4],20,TRUE)))
dbpmn[4]<-
 ifelse(as.character(dbpmn[,1]) == as.character(dbpmn[,(2)]),
 dbpmn[,3],"")
dbpmn
   V1 V2 V3 V4
1   B  D  C   
2   C  A  D   
3   C  B  A   
4   A  B  C   
5   B  D  B   
6   D  D  A  1
7   D  D  D  4
8   B  C  A   
9   B  D  B   
10  D  C  A   
11  A  D  C   
12  A  C  B   
13  A  A  A  1
14  D  C  A   
15  C  D  B   
16  A  A  B  2
17  A  C  C   
18  B  B  C  3
19  C  C  C  3
20  D  D  D  4

I get what I expect, the numeric value of the third element in dbpmn 
where the first two elements are equal. I think what you want is:

dbpmn[4]<-
 ifelse(as.character(dbpmn[,1]) == as.character(dbpmn[,(2)]),
 as.character(dbpmn[,3]),"")
dbpmn
   V1 V2 V3 V4
1   B  D  C   
2   C  A  D   
3   C  B  A   
4   A  B  C   
5   B  D  B   
6   D  D  A  A
7   D  D  D  D
8   B  C  A   
9   B  D  B   
10  D  C  A   
11  A  D  C   
12  A  C  B   
13  A  A  A  A
14  D  C  A   
15  C  D  B   
16  A  A  B  B
17  A  C  C   
18  B  B  C  C
19  C  C  C  C
20  D  D  D  D

Jim



More information about the R-help mailing list