【发布时间】:2022-01-19 22:02:29
【问题描述】:
我有以下数据:
id animal color shape
1 bear orange circle
2. dog NA triangle
3. NA yellow square
4. cat yellow square
5. NA yellow rectangle
如果我运行这段代码:
df1 <- df %>%
pivot_longer(
-id,
names_to = "Variable",
values_to = "Level"
) %>%
group_by(Variable, Level) %>%
summarise(freq = n()) %>%
mutate(percent = freq/sum(freq)*100) %>%
mutate(Variable = ifelse(duplicated(Variable), NA, Variable)) %>%
ungroup()
我可以得到以下输出:
Variable Level freq(n=5) percent
animal bear 1 33.3
dog 1 33.3
cat 1 33.3
color orange 1 25.0
yellow 3 75.0
shape circle 1 20.0
triangle 1 20.0
square 2 40.0
rectangle 1 20.0
但是我还想在每个变量之后添加一行,其中包含总计:
Variable Level freq(n=5) percent
animal bear 1 33.3
dog 1 33.3
cat 1 33.3
total 3 100.0
color orange 1 25.0
yellow 3 75.0
total 4 100.0
shape circle 1 20.0
triangle 1 20.0
square 2 40.0
rectangle 1 20.0
total 5 100.0
我尝试了 mutate 和 summarise 的不同变体,但不断收到错误“参数的无效'类型'(闭包)”。
【问题讨论】:
-
janitor::adorn_total -
您的输入和输出与正在发生的不匹配;初始
NA值在哪里?对我来说,它们仍然存在,但不知何故,它们在您的预期输出中消失了。