Sorry if the title is a bit convoluted, as I didn't know how else to explain this issue. Basically, I'm attempting to mutate a percent of group variable utilizing dplyr
. However, I'm running into an issue where the new calculated variable appears numeric, and even calculates when using summary()
, but will not allow me to call mean()
or sd()
without throwing me the following error:
Warning message:
In mean.default(., group_pct) :
argument is not numeric or logical: returning NA
Here are some examples of what is going on.
data(mtcars)
mtcars %>%
group_by(cyl) %>%
mutate(group_pct = hp / sum(hp)) %>%
summary()
Note: group_pct is calculating correctly when called via summary()
...
data(mtcars)
mtcars %>%
group_by(cyl) %>%
mutate(group_pct = hp / sum(hp)) %>%
mean(group_pct)
...but when I call for the mean here, it cannot complete the function. Even when I use ungroup()
and/or na.rm = TRUE
, the function still doesn't work. I don't understand what the issue is here.
EDIT: For clarification, I'm hoping to do something like this...
mtcars %>%
group_by(cyl) %>%
mutate(group_pct = hp / sum(hp)) %>%
paste0('Words: ', mean(group_pct))
Hoping for this final result:
Words: 0.09375
...which I don't think I can use summarize()
for, hence my non-inclusion of it from the start. Apologies for any inconveniences.
mtcars
with each element of the form"Words: #.###"
? – zack