In R I have a table of people's responses to a multiple choice questionnaire e.g. table1:
subject question1 question2 question3
person1 1 2 1
person2 2 1 3
person3 4 3 1
person4 2 4 2
and I have tables I want to use to combine their answers to the questions to produce a new variable e.g. table2:
Q2=1 Q2=2 Q2=3 Q2=4
Q1=1 1 1 2 2
Q1=2 2 2 2 3
Q1=3 3 3 4 4
Q1=4 4 4 4 5
Where the row# is their answer to Question 1 and the column# is their answer to Question 2. For example, if they answered "3" to Question 1 and "2" to Question 2, I need the corresponding value in row 3/column 2 of the second table i.e. "3".
When I use the code:
table1$combinedq1q2 = (table2[table1$question1, table1$question2])
I'm hoping to end up with:
subject question1 question2 question3 combinedq1q2
person1 1 2 1 1
person2 2 1 3 2
person3 4 3 1 4
person4 2 4 2 3
but instead, R is generating a bajillion columns named combinedq1q2.1, combinedq1q2.2, combinedq1q2.3, etc... I don't understand why this is happening or how to fix it. ): I'd appreciate any help!
I did look at this thread and if I can't find any other solution I'll just copy the code from there without really understanding it. But since what I'm looking up values by is the same as the row and column numbers, I was hoping there would be a simpler solution.
Thanks!
EDIT: Thank you for the responses! I added row and column names to my Table 2 to clarify. I'm trying to use the answers to Question 1 and Question 2 to look up/access the value of a third variable in Table 2 (and I already have Table 2; I do not need to generate it). Also, combinedq1q2 just happened to always match question1 in my previous example, so I added another person/row to show that this won't always be the case.
I'll try what was suggested so far, although I'm confused about people saying I'll get combinedq1q2=5 for person3.
combinedq1q2seems to just be the same asquestion1and does not match yourtable2.table1$combinedq1q2 <- mapply(function(q1, q2){table2[q1, q2]}, table1$question1, table1$question2)table2(whose definition doesn't really match your explanation), but that you want to access values fromtable2? Or that you want to generatetable2?