Reputation: 179
I have data similar to below. ppt = participant number; condition = experimental condition of trial; difficulty = difficulty level of trial; correct = whether the ppt chose correctly or not (1 = correct, 0 = incorrect); and key_rt is participant reaction time when making their choice
data <- data.frame(ppt = rep(c(50, 51, 52), each = 20),
condition = rep(c("happy", "sad", "neutral"), times = 20),
difficulty = rep(c(1, 2, 3, 3, 2, 1, 2, 3, 1, 1)),
correct = rep(0:1, times = 15, each = 2),
key_rt = runif(15))
I'd like to apply a function to this data. The data I am applying this function to now is slightly more complex because there are different experimental conditions and difficulty levels, so I have used some for loops within my code for which I apply the function to.
conds = c("happy", "sad", "neutral")
diffs = c(1, 2, 3)
df <- data %>%
for (conds in condition) {
for (diffs in difficulty) {
group_by(ppt) %>%
summarise(Pc = mean(correct),
VRT = var(key_rt[correct==1]),
MRT = mean(key_rt[correct==1]),
out = list(my_fun(Pc, VRT, MRT, n()))) %>%
unnest_wider(out)
}
}
However, the df does not store within the global environment, and there is no error message, so I'm struggling to figure out where I have gone wrong here. I want to apply the function separately to the experimental conditions and difficulty levels for each participant.
The desired outcome would look like below (and columns for Ter but there was no space to add them here):
v_1_happy | v_2_happy | v_3_happy | a_1_sad | a_2_sad | a_3_sad |
---|---|---|---|---|---|
1.80 | 2.00 | 2.55 | 1.57 | 1.99 | 2.01 |
Upvotes: 0
Views: 41
Reputation: 1250
Try lapply
and split
functions. First, you must create a function make the job for every subset (every condition and difficulty combinations). Then apply the function for every subset with lapply
. split
will help you to create the subsets. Try this:
my_fun <- function(data){
data %>%
group_by(ppt) %>%
summarise(Pc = mean(correct),
VRT = var(key_rt[correct==1]),
MRT = mean(key_rt[correct==1]),
out = list(EZ(Pc, VRT, MRT, n()))) %>%
unnest_wider(out)
}
library(dplyr)
library(tidyr)
lapply(split(data,paste(data$condition,data$difficulty)),my_fun)
The Output is a list of results by ppt for every subset.
Upvotes: 2