I have a data.frame which contains an ID number and scaled responses from a survey:
df(responses)
ID X1 X2 X3 X4
A1 1 1 2 1
B2 0 1 3 0
C3 3 3 2 0
I also have a data.frame that is used as a key:
df(key)
X Y Z
2 1 1
3 2 2
4 3 4
I am trying to write a script that will calculate an X, Y, and Z score for each participant, where the X score is the sum of the responses for the questions listed under X in the key.
e.g. the X score for participant A1 would be equal to the sum of X2, X3, and X4in the A1 row (1+2+1 = 4).
The desired output is:
df(output)
ID X Y Z
A1 4 4 3
B2 4 4 1
C3 5 8 6
However, I am currently struggling to be able to index the data.frame responses using the values in key. My current state is:
#store scale names
scales <- c(colnames(key))
#loop over every participant
for (i in responses$ID){
#create temporary data.frame with only participant "i"s responses
data <- subset(responses, ID == i)
#loop over each scale and store the relevant response numbers
for (s in scales){
relevantResponses <- scales[c(s)]
#create a temporary storage for the total of each scale
runningScore <- 0
#index each response and add it to the total
for (r in relevantResponses){
runningScore <- runningScore + data[1,r]
However I am getting the error:
Error in `[.data.frame`(data, 1, r) :
undefined columns selected
Is there a better way of doing the indexing rather than the nested loops?