0
$\begingroup$

I have a CSV that I need to clean up / organize in a usable way using R. I need to group by the property ID and then want to take all the unique years for the defor year column and make each year into a sperate column with the amount of deforestation for that year. My data frame / CSV looks like this:

Prop_ID deforYear   deforHA
1           2010         15
1           2011         0
1           2012         10
2           2010         35
2           2011         45
2           2012         0

and I want the output to look like this:

Prop_ID defor_2010  defor_2011 defor_2012
1               15           0         10
2               35          45          0

I'm assuming I use the group_by function in dplyr but I can't seem to figure it out.

$\endgroup$

1 Answer 1

0
$\begingroup$

This very simple using the pivot_wider function from tidyr:

library(tidyr)

df <- data.frame(
  Prop_ID = c(1, 1, 1, 2, 2, 2),
  deforYear = c(2010, 2011, 2012, 2010, 2011, 2012),
  deforHA = c(15, 0, 10, 35, 45, 0)
)

df %>% 
    pivot_wider(names_from=deforYear, values_from=deforHA, names_prefix="deforYear_")

# result
  Prop_ID deforYear_2010 deforYear_2011 deforYear_2012
1       1             15              0             10
2       2             35             45              0
$\endgroup$
1
  • $\begingroup$ Thanks, that worked perfectly! $\endgroup$
    – SpookyDLX
    Commented Feb 10, 2021 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.