jeudi 4 février 2021

How can I write a function to take the mean in a survey?

Hello I am attempting to write a code/function that can give me the mean/average of a set of scores for each data sets, but I need some help.

Below is an example. I need this function to give me the sum of the scores. The participant could select on a scale of 0-101. But for numbers 2, 5 , and 6. I need to take the reverse score. Lastly I need to take the mean. So the score divided by 6. The expected outcome (the answer) the score = 62 and the mean is 10.33

data Question Scores
1 ''I feel tense'' 76
2 ''I am calm'' 90
3 ''I am excited'' 52
4 ''I am worried'' 65
5 ''I am satisfied'' 90
6 ''I am relaxed'' 90

The problem is I need to code to be universal so I can use it for each data set I have. Because the questions for each participant is given in random order. For example (number one ''I feel tense'') can be in the 5 position and so forth. Thus I am thinking I need a if else statement, but I am a total beginner in R. maybe (if ''I am calm'', do this else do this etc.? )

I have a code that I wrote that works! but it is not very universal because I have to go in a change each data set to match the questions. I would really appreciate some insight or help writing this function.


My code that works for one data set, its kinda long and bad looking. Also its based on the actual data I am working on in Excell that's why its named different.(Data c and data w is just giving me access to the specific places I wanted )

Data_c = DATA1$choice #Change here! 
Data_w = DATA2$word

I have to Change each Question based on if I need the score to be reversed or not. I commented out what I do not use.

Q1 = abs(Data_c[1]-101)
#Q1 = (Data_c[1])

#Q2 = abs(Data_c[2]-101)
Q2 = (Data_c[2])

Q3 = abs(Data_c[3]-101)
#Q3 = (Data_c[3])

Q4 = abs(Data_c[4]-101)
#Q4 = (Data_c[4])

#Q5 = abs(Data_c[5]-101)
Q5 = (Data_c[5])

#Q6 = abs(Data_c[6]-101)
Q6 = (Data_c[6])

df1 <- data.frame(Questions = Data_w,scores = c(Q1, Q2, Q3, Q4, Q5, Q6))

sum = df1$scores[1]+df1$scores[2]+df1$scores[3]+
df1$scores[4]+df1$scores[5]+df1$scores[6]

A = mean(sum/6)

Thank you in advance for reading this and insight

Aucun commentaire:

Enregistrer un commentaire