lundi 31 juillet 2017

If-statement / how to include different levels of a variable in calculating sd in R?

I have a dataset of the form

     nutscode nutslevel country GDP year
     at12     nuts2     at      200 1990     
     be1      nuts1     be      300 1990
     be2      nuts1     be      350 1990
     de3      nuts1     de      200 1990
     es23     nuts2     es      180 1990

where each country gets assigned a NUTS level, with most being NUTS 2, with some exceptions. The nutscode variable varies according to the nutslevel variable.

Now, I am trying to calculate standard deviation of GDP for 1990, and want to include all NUTS2 countries AND the exceptions (Germany and Belgium, for instance). My standard deviation formula for everything NUTS2 is pretty straightforward:

    sd(alldata$gdpcapita[alldata$year=="1990" & alldata$nutslevel=="nuts2"])

But since I want to add those country exceptions too, I'd need sth like

    sd(alldata$gdpcapita[alldata$year=="1990" & alldata$nutslevel=="nuts1" for specific countries and NUTS2 otherwise])

I'm thinking of creating a variable that would take NUTS1 values if the country variable has the values of "be"|"de"|"el"|"nl"|"uk", or if the nutscode identifier has "be"|"de"|"el"|"nl"|"uk" in the name, and then use that for standard deviation. Something like

   alldata$var <- factor (with (alldata, ifelse ((country == "be"|"de"|"el"|"nl"|"uk"), nutslevel=="nuts1", nutslevel=="nuts2")))

But then this happens

   Error in country == "be" | "de" : operations are possible only for numeric, logical or complex types

or

   alldata$var <- factor (with (alldata, ifelse (((grepl("be"|"de"|"el"|"nl"|"uk", alldata$nutscode)), nutslevel=="nuts1", nutslevel=="nuts2")))

And error again

   Error: unexpected ',' in "alldata$var <- factor (with (alldata, ifelse (((grepl("be"|"de"|"el"|"nl"|"uk", alldata$nutscode)),"

What am I doing wrong? I am stuck, not sure how to proceed now and would be grateful for any guidance. I'm totally new to R, so I have no idea if there is a more sophisticated way of writing all this, or what those error messages mean. Thank you!

Aucun commentaire:

Enregistrer un commentaire