[R] an unsophisticated question about recoding in a data frame with control structure if {}

Whitt Kilburn kilburnw at gvsu.edu
Wed Oct 1 11:05:17 CEST 2008


Hello all, 

I apologize for a terribly simple question.  I'm used to using Stata and am trying to `switch' over to R.  

I would like to recode a vector in a data frame when the value of it meets the following condition:  if (dataframe$factor=='3'){dataframe$thevector<-(an arithmetic mean).  What I would like to result is the creation of a new variable within the data frame for which all observations that =='3' get the mean.  Yet, I receive an error message that R is only reading the first element of the factor:  

Warning message:
In if (nes2004$Rrace2 == "1") { :
  the condition has length > 1 and only the first element will be used

As the command in question actually appears: 
if (nes2004$Rrace2=='3') {
nes2004$Hethno<-(((nes2004$Hint-nes2004$Wint)+(nes2004$Hint-nes2004$Bint)+(nes2004$Hint-nes2004$Aint)+(nes2004$Hwork-nes2004$Wwork)+(nes2004$Hwork-nes2004$Bwork)+(nes2004$Hwork-nes2004$Awork)+(nes2004$Htrus-nes2004$Wtrus)+(nes2004$Htrus-nes2004$Btrus)+(nes2004$Htrus-nes2004$Atrus))/9) }

The other problem here too, is that each of these variables contain varying counts of NA observations.  

I've tried to work around this by using ifelse, and other commands, but I can not figure out where to begin re-thinking how I do this.  Any guidance would be appreciated.  

Thank you.  
Whitt 



****************************************
H. Whitt Kilburn, Ph.D.
Assistant Professor
Grand Valley State University
Political Science Department
1124 AuSable Hall
1 Campus Drive
Allendale, MI 49401-9403
Phone:(616) 331-8831
Fax:(616) 331-3550
http://faculty.gvsu.edu/kilburnw



More information about the R-help mailing list