[R] Odp: Error "the condition has length > 1 and only the first element will be used"
Petr PIKAL
petr.pikal at precheza.cz
Fri Jun 19 14:05:40 CEST 2009
Hi
r-help-bounces at r-project.org napsal dne 19.06.2009 09:26:57:
> 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
> }
> }
>
First few guesses
data is a data frame with more than one row.
data$country_str is a vector of country strings like in state.abb
data$ecdfs1 are some numeric data
you want to compute ecdfs1 mean for each country_str
If yes then maybe
aggregate(data$ecdfs1, list(data$country_str), mean)
could do it
If some of above is not valid so please give some more info to poor
helpers.
Besides, the error comes from
?"if"
cond
A length-one logical vector that is not NA.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Conditions of length greater than one are accepted with a warning, but
only the first element is used. Other types are coerced to logical if
possible, ignoring any class.
For comparing vectors use ifelse instead
Regards
Petr
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list