如何将R中的多行值转换为一行[重复]

问题描述 投票:0回答:1

我正在简化和总结我的数据,以便我可以对其运行方差分析,因此我想将一列中的行压缩为更少的行。我觉得只有看数据才有意义,

这是我的数据的简化版本:


参与者ID 问题_编号 问题_评级_类型 平均参与者评分
10556 1 1 2.303922
10556 1 2 2.507365
10556 2 1 2.303922
10556 2 2 2.507365
10556 3 1 2.303922
10556 3 2 2.507365
10556 4 1 2.303922
10556 4 2 2.507365

这就是我想要的样子:

参与者ID 问题_范围 问题_评级_类型 平均参与者评分
10556 1 - 6 1 2.303922
10556 1 - 6 2 2.507365
10557 1 - 6 1 3.557155
10557 1 - 6 2 1.507365
10558 1 - 6 1 3.556154
10558 1 - 6 2 1.657311
10559 1 - 6 1 2.357325
10559 1 - 6 2 1.522221

因此,我想压缩 Question_numbers,以便平均值显示为不同的值,而不是与每个 Question_number 一起打印,因为它们代表每个参与者的平均问题评分的问题 1-6 的平均值。我使用 tidyverse 软件包等,所以如果人们有使用这些有用的软件包的建议!!

r group-by summarize simplify mutate
1个回答
0
投票

如果我明白您想要做什么,您可以使用

summarise()
,按参与者 ID 和问题评分类型进行分组:

library(tidyverse)  

dat <- read.table(textConnection("ParticipantID Question_number Question_Rating_Type    Avg_Participant_Rating
10556   1   1   2.303922
10556   1   2   2.507365
10556   2   1   2.303922
10556   2   2   2.507365
10556   3   1   2.303922
10556   3   2   2.507365
10556   4   1   2.303922
10556   4   2   2.507365"), header=TRUE)

dat %>% group_by(ParticipantID, Question_Rating_Type) %>% 
  summarise(Question_number = glue::glue("{min(Question_number)}-{max(Question_number)}"), 
            Avg_Participant_Rating = mean(Avg_Participant_Rating)) %>% 
  select(1,3,2,4)
#> `summarise()` has grouped output by 'ParticipantID'. You can override using the
#> `.groups` argument.
#> # A tibble: 2 × 4
#> # Groups:   ParticipantID [1]
#>   ParticipantID Question_number Question_Rating_Type Avg_Participant_Rating
#>           <int> <glue>                         <int>                  <dbl>
#> 1         10556 1-4                                1                   2.30
#> 2         10556 1-4                                2                   2.51

创建于 2024-02-06,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.