[R] using nested ifelse and rowSums to create new variable?

Tony N. Brown tony.n.brown at vanderbilt.edu
Tue Nov 21 21:26:21 CET 2006


Dear R-help community,

If I have a data.frame df as follows:

> df
   x1 x2 x3 x4 x5 x6
1   5  5  1  1  2  1
2   5  5  5  5  1  5
3   1  5  5  5  5  5
4   5  5  1  4  5  5
5   5  1  5  2  4  1
6   5  1  5  4  5  1
7   5  1  5  4  4  5
8   5  1  1  1  1  5
9   1  5  1  1  2  5
10  5  1  5  4  5  5
11  1  5  5  2  1  1
12  5  5  5  4  4  1
13  1  5  1  4  4  1
14  1  1  5  4  5  5
15  1  5  5  4  5  1
16  1  1  5  5  5  1
17  5  5  5  2  2  5
18  1  5  1  5  5  5
19  5  5  5  2  4  5
20  1  1  5  2  4  5

How can I create a variable that captures the pattern of responses 
and counts across rows?

I used the ifelse function and that works fine for the first two 
conditions (see R code below). But I need help figuring out how to 
count the number of scores in each row for columns x3, x4, x5, and 
x6 that are less than 4, conditional upon an ifelse. I then want to 
assign a value to the new variable based upon the count.

The new variable I want to create is called dep. Here's my R code:

dep<-with(df,
  ifelse((x1==5) & (x2==5), 0,
  ifelse((x1==1 & x2==1), 1,

  ifelse((x1==1 & x2==5) | (x1==5 & x2==1) &
  (rowSums(df[ ,c(x3, x4, x5, x6)]<4) ==1), 2,
  ifelse((x1==1 & x2==5) | (x1==5 & x2==1) &
  (rowSums(df[ ,c(x3, x4, x5, x6)]<4) ==2), 3,
  ifelse((x1==1 & x2==5) | (x1==5 & x2==1) &
  (rowSums(df[ ,c(x3, x4, x5, x6)]<4) ==3), 4,

99))))))

dep
 0  1  2 99
 6  3  6  5

I expected dep to range from 0 to 4 and its length to be equal to 
20.

Thanks in advance for your help and suggestions.

Version: R 3.2.1
OS: Windows XP


---------------------------------------
Tony N. Brown, Ph.D.
Assistant Professor of Sociology
Vanderbilt University
Phone:  (615) 322-7518
Fax:    (615) 322-7505
Email:  tony.n.brown at vanderbilt.edu



More information about the R-help mailing list