想知道如何在 R 中創建一個包含不同計算結果的表。這是一個使用 mtcars df 的示例
# Load tidyverse
library(tidyverse)
# Select only cyl vs and am from mtcars for simplicity
mt_select <- select(mtcars, c(cyl, vs, am))
# Here is the table I wish to make using some type of looping function
# (I have like 40 variables in actual dataset)
freq_table <- mt1 %>% group_by(cyl) %>%
summarise(n = n(),
vs_sum = sum(vs),
vs_perc = sum(vs)/n*100,
am_sum = sum(am),
am_perc = sum(am)/n*100)
print(freq_table)
這是我的嘗試。我無法弄清楚的主要問題:
- 包括“0”答案的總和,
- 我不知道如何添加百分比列
- 不知道如何將這些全部合并到一張表中
# make a vector to loop through
mt_vars <- names(mt_select)
# Loop to make tables
for (i in mt_vars){
mt_select %>%
group_by(cyl) %>%
count_(i) %>%
print()
}
幾個月來一直試圖弄清楚如何制作這個,但總是決定我不需要桌子或其他東西。任何幫助是極大的贊賞!!
uj5u.com熱心網友回復:
您沒有提供預期的輸出,但我認為解決您的問題的關鍵可能是將您的資料轉換為長格式。這可能會讓你做你想做的事,而不需要任何回圈。例如,mtcars作為輸入:
library(tidyverse)
mtcars %>%
pivot_longer(everything()) %>%
group_by(name) %>%
summarise(
n=n(),
valueSum=sum(value),
valuePct=valueSum/(n*100)
)
# A tibble: 11 × 4
name n valueSum valuePct
<chr> <int> <dbl> <dbl>
1 am 32 13 0.00406
2 carb 32 90 0.0281
3 cyl 32 198 0.0619
4 disp 32 7383. 2.31
5 drat 32 115. 0.0360
6 gear 32 118 0.0369
7 hp 32 4694 1.47
8 mpg 32 643. 0.201
9 qsec 32 571. 0.178
10 vs 32 14 0.00438
11 wt 32 103. 0.0322
這接近你想要的嗎?如果您只想處理列的子集,請everything()在filter旋轉之后或select旋轉之前替換您需要的內容。
另外,我不確定您要計算的百分比是多少。
value和name是 和 的names_to默認values_to值pivot_longer()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/481522.html
