Subtracting two columns with conditions

Hi

I have this df called new_clean_m here.

I used these two libraries
library(tidyvere)
library(readr)

using this code: to calculate the mean, sd, cv within the following group_by conditions

new_ce = new_clean_m %>%
  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))

Q: I need to subtract "stim_ending_t values" from the mean "m" so I can get something called constant error.

Here is what I tried to do this:

df_ce = new_clean_m %>%
    group_by(stim_ending_t, visbility, soundvolume, Opening_text) %>%
    summarize(m = mean(key_resp_2.rt),
              sd = sd(key_resp_2.rt),
              ce = (stim_ending_t - m),
              coefVar = cv(key_resp_2.rt))

I got the following error: Column `ce` must be length 1 (a summary value), not 210

and this

df_ce = new_clean_m %>%
    group_by(stim_ending_t, visbility, soundvolume, Opening_text) %>%
    summarize(ce = (stim_ending_t - m))

I got the following error: Error: object 'm' not found

Try adding the new column with mutate() after doing the summarize.

new_ce = new_clean_m %>%
  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)) %>% 
  mutate(ce = (stim_ending_t - m))
3 Likes

Hi, first off a reproducible example, called a reprex helps quite a bit in attracting responses. Here's what yours should look like:

library(tidyverse)
library(readr)

# cv missing from namespace
cv <- function(x,y){
  x/y
}

url <- "https://github.com/MohJumper/VisualAuditoryModality/raw/master/new_clean_m.csv"
new_clean_m <- read.csv(url)


df_ce <-  new_clean_m %>%
  group_by(stim_ending_t, visbility, soundvolume, Opening_text) %>%
  summarize(m = mean(key_resp_2.rt),
            sd = sd(key_resp_2.rt),
            #ce = (stim_ending_t - m), # stim_ending_t varies, m is constant
                                      # ∴ ce is not an atomic vector
            coefVar = cv(sd,m))

Created on 2019-09-11 by the reprex package (v0.3.0)

While I was composing @FJCC beat me to the mutate part. If you use my cv function,

coefVar = cv(sd,m)) %>% 
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.