0

I want to get the prop inside each factor using dplyr. The desired result appears in desired$prop Thanks in advance :))

data <- data.frame(
          team = c("a", "a", "a", "b", "b", "b", "c", "c", "c"),
             country = c("usa","uk",
                         "spain","usa","uk","spain","usa","uk","spain"),
         value = c(40, 20, 10, 50, 30, 35, 50, 60, 25)
  )
desired <- data.frame(
          team = c("a", "a", "a", "b", "b", "b", "c", "c", "c"),
                  country = c("usa",
                              "uk","spain","usa","uk","spain","usa","uk",
                              "spain"),
         value = c(40, 20, 10, 50, 30, 35, 50, 60, 25),
                     prop = c(0.285714286,0.181818182,0.142857143,0.357142857,
                              0.272727273,0.5,0.357142857,0.545454545,
                              0.357142857)
       )

1 Answers1

0

@MrFlick is right. And also faster than I am.

library(dplyr)

df <- data %>%
  group_by(country) %>%
  mutate(prop = value/sum(value))
TTS
  • 1,818
  • 7
  • 16