gpt4 book ai didi

r - 如何使用 R 计算选项的响应百分比?

转载 作者:行者123 更新时间:2023-12-02 19:23:42 24 4
gpt4 key购买 nike

这是我的数据框的示例:

    Question Student Option
1 1 1 4
2 1 2 1
3 1 3 1
4 1 4 5
5 2 1 3
6 2 2 2
7 2 3 2
8 2 4 1

我正在尝试计算每个问题的选项 0-5 的响应百分比。我设法通过这样的问题计算每个选项的响应百分比:

Global_Response <- group_by(ExamData,Question) %>% #group data by question
summarise(Global_0 = length(which(Option=="0"))/length(Option)*100, #Percentage of response option "0" by question
Global_1 = length(which(Option=="1"))/length(Option)*100,
Global_2 = length(which(Option=="2"))/length(Option)*100,
Global_3 = length(which(Option=="3"))/length(Option)*100,
Global_4 = length(which(Option=="4"))/length(Option)*100,
Global_5 = length(which(Option=="5"))/length(Option)*100)

最后,我想要一个新的数据框,其中包含每个选项的响应百分比。与此示例类似:

Question Global_0 Global_1 Global_2 Global_3 Global_4 Global_5
<int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0 50.0 0 0 25.0 25.0
2 0 25.0 50.0 25.0 0 0

现在,我想做同样的事情,但只需几行代码。我尝试过 for 循环,但没有成功。我不知道什么更适合做我想做的事。

最佳答案

也许这可以帮助......

df <- dplyr::tibble(
Question=c(1,1,1,1,1,1,2,3),
Student=c(1,2,3,4,5,6,1,1),
Option=c(4,1,1,3,4,2,5,1)
)

global_response <- df %>%
dplyr::count(Question,Option) %>%
dplyr::group_by(Question) %>%
dplyr::mutate(pct=n/sum(n)*100) %>%
dplyr::ungroup()

# A tibble: 6 x 4
Question Option n pct
<dbl> <dbl> <int> <dbl>
1 1 1 2 33.3
2 1 2 1 16.7
3 1 3 1 16.7
4 1 4 2 33.3
5 2 5 1 100
6 3 1 1 100

如果您想要更宽的格式,就这样做

global_response %>%
tidyr::pivot_wider(id_cols=Question,
names_from=Option,
values_from=pct,
values_fill=list(pct=0))

# A tibble: 3 x 6
Question `1` `2` `3` `4` `5`
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 33.3 16.7 16.7 33.3 0
2 2 0 0 0 0 100
3 3 100 0 0 0 0

关于r - 如何使用 R 计算选项的响应百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62674834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com