views:

79

answers:

2

Hi R experts,

I am providing this example data to get my question across.

aid=c(1,2,3,4,5,6,7,8,9,10)
foson=c(0,1,2,0,6,9,0,0,3,0)
fosof=c(0,0,2,3,0,0,0,5,0,0)
data=data.frame(aid,foson,fosof)

Now, I need to create a new variable (column) named data$hist with the following conditions:

if foson==0 and fosof==0, then hist = 0;
if foson >=1 and fosof==0, then hist = 1;
if foson==0 and fosof>=1, then hist = 2; and
if foson>=1 and fosof>=1, then hist = 3

I tried to use the "ifelse" function but fell short.

I hope that the question is clear enough.

Thanks for all the help,

Bazon

+3  A: 

One potential solution is to do the following

data$hist = (data$foson >=1) + (data$fosof >=1)*2

This should give you the desired result.

Ramnath
Hi Ramnath, That worked! I'm just trying to fully understand the entire line (syntax)..... especially the *2 bit at the end of the line.Bazon
Bazon
It uses the fact that logical values (TRUE, FALSE) can also be used numerically (1,0). It just sets all foson to 1 or 0 and all fosof to 2 (1*2) or 0 and adds them. It was actually a great solution... something a C programmer would think of.
John
+1  A: 

The solution by Ramnath is excellent, but to do it with ifelse you could do it this way:

data$hist <- ifelse(data$foson>=1,ifelse(data$fosof>=1,3,1),ifelse(data$fosof>=1,2,0))

This would however mean that where any of foson or fosof are <1 it would select the option for ==0, but it seems from your data this would not be an issue.

James