Creating a new variable using two columns when they satisfy certain conditions using R

I provide data from this example to ask a question.

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 using the ifelse function but did not understand.

Hope the question is clear enough.

Thanks for the help,

Bazon

+3
source share
2 answers

Ramnath's solution is excellent, but for this with help ifelseyou can do it like this:

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

, , foson fosof <1, ==0, , , .

+2

,

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

.

+4

Source: https://habr.com/ru/post/1762978/


All Articles