[R] Error "the condition has length > 1 and only the first element will be used"

Casey Quinn caseyquinntravelling at googlemail.com
Fri Jun 19 09:26:57 CEST 2009


Ahoy. I'm trying to run a function for each country in a multinational  
dataset. Keeping it simple, an example is


for(j in 11:14) {
if(data$country_str == "j") {

mu <- mean(data$ecdfs1)
} else {
mu <- 0
}
}

The number of countries is greater and the functions are more complex, but  
this fails just the same. The consistent error is


In if (data$country_str == "j") { :
   the condition has length > 1 and only the first element will be used

Using the inelegantly workable

if(data$country_str == "11") {

mu <- mean(data$ecdfs1)
} else {
mu <- 0
}

And repeating manually I still get the same error.

For those who know both, in Stata I did this with the foreach command (but  
I don't trust Stata's results for my ML estimates), although for summary  
statistics the bysort command would be appropriate. I can't find a clear  
analog in R.

Can anybody explain just what the error is, and how to fix it? Which  
'condition' is inappropriately lengthed - the country string or the values  
it takes?

Neither the  manual nor examples online match my problem - or at least not  
apparently to me. I've tried an ifelse but it runs the functions for every  
observation depending upon whether or not the condition is met. I only  
want 13 sets of output, not 30,000.

Do I need to just break my dataset up into the countries and do it the  
long way?


Much appreciated, thank you.

Casey




More information about the R-help mailing list