I want to calculate a moderation analysis in a multilevel model. I have 20 taskblocks (lvl 1) for 33 participants (lvl 2). For my relevant IV and DV I have already written a loop that works:
for(i in 1:length(participants)) {
participant.sub <- df[df$participant == participants[i],]
participant.sub <- participant.sub[!is.na(participant.sub$participant),]
for (j in 1:20) {
block.sub <- participant.sub[participant.sub$block == j,]
data.row <- c(unique(block.sub$participant),
j,
block.sub$slider_mentaleffort.response[!is.na(block.sub$slider_mentaleffort.response)],
block.sub$goal[!is.na(block.sub$goal)],
block.sub$sum_correct[!is.na(block.sub$sum_correct)])
data.row <- data.row[2:6]
dummy.df <- rbind(dummy.df, data.row)
}
}
Now I want to include the moderators. The moderator variables are likert-scales that got answered before the experiment started. Each person has exactly one value on each scale. How do I add those values to the current loop/data frame, so that I can continue with lmer?
I tried this
for(i in 1:length(participants)) {
participant.sub <- df[df$participant == participants[i],]
participant.sub <- participant.sub[!is.na(participant.sub$participant),]
for (j in 1:20) {
block.sub <- participant.sub[participant.sub$block == j,]
data.row <- c(unique(block.sub$participant),
j,
block.sub$slider_mentaleffort.response[!is.na(block.sub$slider_mentaleffort.response)],
block.sub$goal[!is.na(block.sub$goal)],
block.sub$sum_correct[!is.na(block.sub$sum_correct)],
block.sub$slider_effort.response[!is.na(block.sub$slider_effort.response)],
block.sub$slider_talent.response[!is.na(block.sub$slider_talent.response)],
block.sub$slider_luck.response[!is.na(block.sub$slider_luck.response)],
block.sub$slider_taskdiff.response[!is.na(block.sub$slider_taskdiff.response)])
data.row <- data.row[2:9]
dummy.df <- rbind(dummy.df, data.row)
}
}
and
for(i in 1:length(participants)) {
participant.sub <- df[df$participant == participants[i],]
participant.sub <- participant.sub[!is.na(participant.sub$participant),]
for (j in 1:20) {
block.sub <- participant.sub[participant.sub$block == j,]
data.row <- c(unique(block.sub$participant),
j,
block.sub$slider_mentaleffort.response[!is.na(block.sub$slider_mentaleffort.response)],
block.sub$goal[!is.na(block.sub$goal)],
block.sub$sum_correct[!is.na(block.sub$sum_correct)],
block.sub$slider_effort.response,
block.sub$slider_talent.response,
block.sub$slider_luck.response,
block.sub$slider_taskdiff.response)
data.row <- data.row[2:9]
dummy.df <- rbind(dummy.df, data.row)
}
}
But to no avail.
It is better to use dpylr and slice the data in the rows I wanted, before merging them into one frame, that leaves out the na's
It is the more elegant, flexible and shorter way than looping.