Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

loops - How can I reverse a value in R

I have a question. I am trying to take the mean of a data set from a questionnaire but I need to reverse score some results.

So the participants rated their levels of anxiety on a scale of 0-100. There were six 0-100 questions total. The higher score indicated higher levels of stress. but for some questions a high level of stress is considered to be a lower score.

data | Scores 

1      76  
2      90  
3      52  
4      65  
5      90  
6      90 

The questions I need to reverse are 2,4,5 Example: For question 2 there is a score of 90. I need it to show up as a score of 11 instead. (scales is 0-100) 101-90 = 11.

after reading some forums on the internet, I am guessing I need to minus -101 on the targeted questions. but How can I write a code for R to do this for me for each data set.

Thanks in advance.

question from:https://stackoverflow.com/questions/65882748/how-can-i-reverse-a-value-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should work without a for loop.

df <- data.frame(data = c(1, 2, 3, 4, 5, 6),
                 scores = c(76, 90, 52, 65, 90, 90))
df
#   data scores
# 1    1     76
# 2    2     90
# 3    3     52
# 4    4     65
# 5    5     90
# 6    6     90

# Setup and change specific rows
rows_to_change <- c(2, 4, 5)
df[rows_to_change, 2] <- 101 - df[rows_to_change, 2]

df
#   data scores
# 1    1     76
# 2    2     11
# 3    3     52
# 4    4     36
# 5    5     11
# 6    6     90

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...