mardi 11 décembre 2018

R (dplyr/tidyverse) | Using mutate_at to construct a series of new variables using if_else statements

I'm relatively new to this site and to the world of programming, so my apologies if this has already been asked.

Here's a modified version of a data frame I'm currently working with (truncated to make things easier to diagnose):

  COUNTRY          b_2010 c_2010 b_2011  c_2011   
1 Australia          50     62     67     56     
2 Austria            50     48     48     95      
3 Belgium            50     26     67     25      
4 Bulgaria           50     54     42     64      

Let's assume that I want to create a series of variables indicating that a country has a value equal to or greater than 50 for each existing variable in a given year.

I can do so by running something like this:

dataframe %>% mutate(d_2010 = if_else(b_2010 & c_2010 >= 50, "A", "B"),
                     d_2011 = if_else(b_2011 & c_2011 >= 50, "A", "B"))

This should produce the indicator variables I'm looking to construct, but the process will get awfully taxing if I have a lengthy time series. I'm sure there's a way to go about doing this more efficiently (using mutate_at or some other function), but I haven't been able to figure it out.

Can someone out there help me out?

Thanks!

Aucun commentaire:

Enregistrer un commentaire