create prop table using dplyr

Hello,
I need to create a prop.table column in a tibble object using dplyr.
However, I 'm not sure. Here is my data:

responses=c("yes","no","yes","no","yes","no")
cases=c(100,500,200,600,400,1000)
zone=c(1,1,2,2,3,3)
data=data.frame(responses,zone,cases)
data=as_tibble(data)
data$responses=factor(data$responses)
data
data %>%group_by(zone) %>%  mutate(percentage=cases/sum(cases))


I need to compute a prop.table considering yes/no response on every zone.
I noticed I couldn't use prop.table (It was complex for me).
Also, if I try to perform the same operation but using cases as integers, I obtain just "1" as result.
I need to convert It to dbl (with hablar) in order to gain the decimal places.
Anyway, does my code look ok?
Thanks for your time and interest.

your code looks fine to me, it works...
if you specifically want to use prop.table/proportions, then it doesnt really involve dplyr, it relies on using xtabs

(data <- tibble(
  zone = c(1, 1, 2, 2, 3, 3),
  cases = c(100L, 500L, 200L, 600L, 400L, 1000L),
  responses = as.factor(c("yes", "no", "yes", "no", "yes", "no"))
))

(myxt <- xtabs(cases ~ zone + responses, data))

(myprops <- proportions(myxt,"zone"))

(myprops_tbl <- as_tibble(myprops))

I didn't understand your issue with integers.
in my data i have the cases as integers, and your code works fine and gives decimal precision,...

data %>% 
group_by(zone) %>%  
mutate(percentage=cases/sum(cases))

so is that occurring with this code ?

(data <- tibble(
  zone = c(1, 1, 2, 2, 3, 3),
  cases = c(100L, 500L, 200L, 600L, 400L, 1000L),
  responses = as.factor(c("yes", "no", "yes", "no", "yes", "no"))
))
data %>% 
group_by(zone) %>%  
mutate(percentage=cases/sum(cases))

I dont recognise / dont have context for any of the terms used by you here...

 convert(dbl(var_integer))

what libraries are the functions from, and what is var_integer in this context ? how would it fit with the example we are looking at?

1 Like

I tried working with integers, always using dplyr, and if I don't do convert(dbl(var_integer)), it computes only 1.
I have no idea why that happens.