Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

adding percent calculation to dataframe

I would like to create a table with frequency counts and percentages. I have the frequency counts and calculated the percentages. When I try to add it to the dataframe, it’s doesn’t add the calculations to the dataframe. The code:

fpanel <- rename(count(surveydata, panel), Freq = n)
fpanel$proportion <- fpanel$Freq / dim(surveydata)[1]
fresponder <- rename(count(surveydata, panel, responder), Freq = n)
fresponder$percent <- c(fresponder[1,3] / fpanel[1,2], 
                        fresponder[2,3] / fpanel[1,2],
                        fresponder[3,3] / fpanel[2,2],
                        fresponder[4,3] / fpanel[2,2],
                        fresponder[5,3] / fpanel[3,2],
                        fresponder[6,3] / fpanel[3,2],
                        fresponder[7,3] / fpanel[4,2],
                        fresponder[8,3] / fpanel[4,2])

And the results:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The calculations are correct without adding to the dataframe but when I add it, I get "<dbl 1>". What kind of error is this and how can I fix it?

>Solution :

fresponder (and fpanel) is a tibble, and unlike data.frames from which they inherit, fresponder[1,2] is still a tibble. As a hasty demonstration, as.data.frame(fresponder)[1,2] should return a numeric instead of a tibble.

class(mtcars)
# [1] "data.frame"
mtcars[1,2]
# [1] 6
tibble(mtcars)[1,2]
# # A tibble: 1 x 1
#     cyl
#   <dbl>
# 1     6

Untested, but try this:

fr <- as.data.frame(fresponder)
fp <- as.data.frame(fpanel)
fresponder$percent <- c(fr[1,3] / fp[1,2], 
                        fr[2,3] / fp[1,2],
                        fr[3,3] / fp[2,2],
                        fr[4,3] / fp[2,2],
                        fr[5,3] / fp[3,2],
                        fr[6,3] / fp[3,2],
                        fr[7,3] / fp[4,2],
                        fr[8,3] / fp[4,2])
# rm(fp,fr)

(But ultimately, calculating $percent here in this way seems very fragile and not resilient/robust.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading