0

I want to divide the percent into Korea and Taiwan separately. I don't have any idea to calculate the percent with ddply fucntion separately.

plot<-ddply(
    data, 
    c("Country", "Here.is.usually.much.garbage.distributed."),
    summarise,
    n=length(Here.is.usually.much.garbage.distributed.),
    percent=((n/sum(plot$n))*100)
)

Is there anyone who knows how to do it?

plot enter image description here

Dilettant
  • 3,267
  • 3
  • 29
  • 29
Sehee Yang
  • 41
  • 2
  • 4
  • Please make your question more [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Unrelated but please avoid names like `plot`(although `df` is also commonly used :)) – NelsonGon Jan 10 '20 at 04:27

2 Answers2

1

Consider switching to dplyr instead of plyr. Try using :

library(dplyr)

data %>% 
  group_by(Country, `Here.is.usually.much.garbage.distributed.`) %>% 
  summarise(n = n()) %>%
  mutate(percent = n/sum(n) * 100)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can use data.table

library(data.table)
setDT(data)[, .(N = .N), by = .(Country, `Here.is.usually.much.garbage.distributed.`)][,
         percent := N/sum(N) * 100][]

With ddply, we get the count and do the percent outside

library(plyr)
out <-ddply(
        data, 
           c("Country", "Here.is.usually.much.garbage.distributed."),
         summarise,
n=length(`Here.is.usually.much.garbage.distributed.`)
 )
out$perc <- out$n/sum(out$n) * 100
akrun
  • 874,273
  • 37
  • 540
  • 662