首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在几个条件下计算R中的平均值

如何在几个条件下计算R中的平均值
EN

Stack Overflow用户
提问于 2019-06-25 02:20:54
回答 2查看 181关注 0票数 0

我正在尝试计算这个数据帧的均值,并将它们分组到一个故事中!我知道如何在excel中使用averageifs,但因为我想最终得到标准差和变异系数(CV),所以我需要在R中学习。

现在我只需要中庸之道。以下是我的条件:

我需要一个表,其中的"stim_ending_t“,即我的时间间隔是从1.0到3.5排成一行的。对于时间间隔,我需要在计算平均值"key_resp_2.rt“时满足这三个条件

仅图像可见性和音量(V=1和s=0)

只有声音(V=0和s=1)

空白(V=0和s=0)

The data frame

Expected out come

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-25 03:02:49

这将计算stim_ending_t (6) x modality (3) = 18组均值。

首先,我生成一些数据,比如您的analysis_vanalysis_a数据帧:

library(dplyr)
library(tidyr)

analysis_v <- data.frame(stim_ending_t = rep(seq(1, 3.5, 0.5), each = 30), 
                         visbility = rep(c(1, 0, 0), 60), 
                         soundvolume = rep(c(0, 1, 0), 60), 
                         key_resp_2.rt = runif(180, 1, 5))

然后我通过管道将对象放入代码块中:

analysis_v %>% 
  group_by(stim_ending_t, visbility, soundvolume) %>% 
  summarize(average = mean(key_resp_2.rt)) %>% 
  ungroup() %>% 
  mutate(key = case_when(visbility == 0 & soundvolume == 0 ~ "blank", 
                         visbility == 0 & soundvolume == 1 ~ "only_sound", 
                         visbility == 1 & soundvolume == 0 ~ "only_images")) %>% 
  select(-visbility, -soundvolume) %>% 
  spread(key, average)

这将导致所请求的输出格式:

# A tibble: 6 x 4
  stim_ending_t blank only_images only_sound
          <dbl> <dbl>       <dbl>      <dbl>
1           1    3.28        3.55       2.84
2           1.5  2.64        3.11       2.32
3           2    3.27        3.72       2.42
4           2.5  2.14        3.01       2.30
5           3    2.47        3.03       3.02
6           3.5  2.93        2.92       2.78

您需要使用analysis_a重复代码块才能获得这些方法。

票数 0
EN

Stack Overflow用户

发布于 2019-07-03 04:57:54

感谢您的帮助@Matthew Schuelke,但是使用您的代码,我每次运行代码时都会得到不同的结果。

下面是我用下面的代码解决这个问题的方法:

name of the new data = (name of the data frame without the parentheses) %>%
  group_by(stim_ending_t, visbility, soundvolume, Opening_text) %>%
  summarize(m = mean(key_resp_2.rt),
            sd = sd(key_resp_2.rt),
            coefVar = cv(key_resp_2.rt))

得到了我想要的结果:

stim_ending_t visbility soundvolume Opening_text               m     sd coefVar
          <dbl>     <dbl>       <dbl> <chr>                  <dbl>  <dbl>   <dbl>
1             1         0           0 Now focus on the Image  1.70  1.14    0.670
2             1         0           0 Now focus on the Sound  1.57  0.794   0.504
3             1         0           1 Now focus on the Image  1.62  1.25    0.772
4             1         0           1 Now focus on the Sound  1.84  1.17    0.637
5             1         1           0 Now focus on the Image  3.19 17.2     5.38 
6             1         1           0 Now focus on the Sound  1.59  0.706   0.444
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56741989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档