jeudi 24 janvier 2019

How to create one variable conditional on other variables in R

I have a very big data-frame like the following:

Region  year    prate   
1       2005     24
1       2006     17
1       2007     56
2       2005     13
2       2006     65
2       2007     43
3       2005     91
3       2006     65
3       2007     12
.....

I want to create a new variable called prate07 in which the variable for year 2007 is the value of prate in that year and the value for other years is 0. Something like the following:

Region  year    prate   prate07
1       2005     24      0
1       2006     17      0
1       2007     56      56
2       2005     13      0
2       2006     65      0 
2       2007     43      43
3       2005     91      0
3       2006     65      0
3       2007     12      12
.....

May someone please help me to find the code for it?

Thanks for the help in advance

I used the following code, but it does not work:

library(tidyverse)
dat2 <- dat %>%
mutate(group2 = str_c("p_rate", year), prate07 = prate) %>%
spread(group2, prate07, fill = 0)

Aucun commentaire:

Enregistrer un commentaire