Home > Enterprise >  How to create percentage column by year and type in R
How to create percentage column by year and type in R

Time:11-07


I have table such as this one
Year Type Value
1991  A  4945
1991  B  525
1991  C  764
1992  A  640
1992  B  3935
1992  D  49
1993  K  49

I would like to generate a new column that calculates the percentage of each type for each year. The types may change per year, and some years only have one type

Eg. The first percentage should be 4945/(4945 525 764)

Any help would be very welcome.
Thank you very much!

CodePudding user response:

Do a group by 'Year' and get the proportions of 'Value'

library(dplyr)
df1 %>% 
    group_by(Year) %>%
    mutate(new = proportions(Value) * 100) %>%
    ungroup

-output

# A tibble: 6 × 4
   Year Type  Value   new
  <int> <chr> <int> <dbl>
1  1991 A      4945 79.3 
2  1991 B       525  8.42
3  1991 C       764 12.3 
4  1992 A       640 13.8 
5  1992 B      3935 85.1 
6  1992 D        49  1.06

Or use base R with ave

df1$new <-  with(df1, ave(Value, Year, FUN = proportions) * 100)

data

df1 <- structure(list(Year = c(1991L, 1991L, 1991L, 1992L, 1992L, 1992L
), Type = c("A", "B", "C", "A", "B", "D"), Value = c(4945L, 525L, 
764L, 640L, 3935L, 49L)), class = "data.frame", row.names = c(NA, 
-6L))
  • Related