Introduction
Sometimes, you will need to create a single variable from two or more existing variables in R. In this blog, we’ll show you some options for doing so.
Create Data
Let’s assume that you administered a survey with four questions that measure a construct such as confidence. Now you need to add the numerical answers to these questions together in order to generate a single confidence score for each participant. First, we’ll create mock data, then we’ll show you how to add them.
q1.a <- runif(30, min=1, max=7)
q1 <- round(q1.a)
q2.a <- runif(30, min=1, max=7)
q2 <- round(q2.a)
q3.a <- runif(30, min=1, max=7)
q3 <- round(q2.a)
q4.a <- runif(30, min=1, max=7)
q4 <- round(q2.a)
Add Data Values
You can create a new value, total, that sums the values of answers to your four survey questions as follows:
total <- q1 + q2 + q3 + q4
Average Data Values
You can create a new value, average, that averages the values of answers to your four survey questions as follows:
average <- (q1 + q2 + q3 + q4) / 4
Multiply Data Values
You can create a new value, mult, that multiplies the values of answers to your four survey questions as follows:
mult <- (q1*q2*q3*q4)
Create a Data Frame
Now you can bring you data together using:
mydata <- data.frame(q1, q2, q3, q4, total, average, mult)
print(mydata)
Here’s what you get (note that, because of the random number generation processes, your results will vary, but the format will look the same):
BridgeText can help you with all of your statistical analysis needs.