blazej blazej - 1 year ago 131
R Question

lm() within mutate() in group_by()

I'm looking for a way to add a column to my data table that consists of

from a
function computed separately for different levels of

I've been suggested to look into
function but that doesn't seem to work with

My working example data looks like this:

outcome data frame

Columns subject, trial and rt are within a
, my goal is to compute
(that I originally made in SPSS) but from a

I've tried

data %<>% group_by (subject) %>%

but it doesn't work - Zre gets computed but not within each subject separately, rather for the entire data frame.

Anyone could please help me? I'm a complete R (and coding in general) newbie, so please forgive me if this question is stupid or a duplicate, chances are I didn't understand other solutions or they where not solutions I looked for. Best regards.

As per Ben Bolker request here is R code to generate data from excel screen shot

#generate data

#Following variable is what I would get after using SPSS code

#make data frame
sym<-data.frame(subject, trial, rt, ZreSPSS)

Answer Source

It looks like a bug in dplyr 0.5's mutate, where lm within a group will still try to use the full dataset. You can use do instead:

sym %>% group_by(subject) %>% do(
    r <- resid(lm(log(rt) ~ trial, data = .))
    data.frame(., r)

This still doesn't match your SPSS column, but it's the correct result for the data you've given. You can verify this by fitting the model manually for each subject and checking the residuals.

(Other flavours of residuals include rstandard for standardized and rstudent for studentized residuals. They still don't match your SPSS numbers, but might be what you're looking for.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download