I wrote a function for one of my regular tasks. I will just try to replicate my issue. Below is a random sample of how my data looks like. its an output of the function dput(mydataframe)
structure(list(respid = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), ssd = c(0,
225, 236, 0, 221, 0, 0, 269, 265, 0), tea = c(228, 0, 269, 0,
258, 241, 0, 222, 0, 256), juice = c(0, 236, 0, 236, 236, 0,
236, 225, 242, 296), vad = c(236, 235, 0, 235, 235, 0, 235, 258,
0, 236), energy = c(0, 235, 236, 235, 0, 236, 235, 0, 236, 0)), .Names = c("respid",
"ssd", "tea", "juice", "vad", "energy"), row.names = c(NA, -10L
), class = c("tbl_df", "tbl", "data.frame"))
now, my objective is to write a function to filter out the non-zero rows in 'ssd' column. Then it would look like this
I wrote the below function in R
SoT <- function(df,key) {
df2 <- df %>% dplyr::filter(key > 0)
df3 <- janitor::adorn_totals(df2, where = "row")
df4 <- tail(df3,1) %>% janitor::adorn_percentages(denominator = "row") %>% janitor::adorn_pct_formatting()
return(df4)
}
my desired output is just the percentage of the summation of the column totals (after filtering for ssd > 0). In the above function, I am just giving the function 2 inputs. 1 is the dataframe and the other is the 'variable name' that I want to filter. I am calling the function like this:
SoT(df1, "ssd")
My desired result in the below pic is the one in green, but I am getting the one in yellow.
This means that the 'filter function' in the code doesn't work. But everything is working fine if I use it simply line by line instead of wrapping inside a function. Any suggestions ?
I haven't removed the images (just for your reference), but I have made the data and code reproducible as suggested.