Any tips on writing a function in R where: An original score (e.g. 50) is adjusted according to a 2nd score for several individuals? First score is 50, and the second score is in a vector ranging from 1 to 5; if the second score is 1 then -5 is added to 50, if it is 2 then -2.5 is added, if 3 then 0 is added, if 4 then 2.5 is added, and if 5 then 5 is added to the original score of 50.
Asked
Active
Viewed 25 times
0
-
1It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Mar 09 '21 at 18:17
1 Answers
0
I think this is more suited to your need:
any_tips <- function(x, score = 50) {
df <- tibble::tibble(sscore = x)
df <- df %>%
dplyr::mutate(
score = dplyr::case_when(
sscore == 1 ~ score - 5,
sscore == 2 ~ score - 2.5,
sscore == 3 ~ score,
sscore == 4 ~ score + 2.5,
sscore == 5 ~ score + 5
)
)
df
}
> any_tips(1:5)
# A tibble: 5 x 2
sscore score
<int> <dbl>
1 1 45
2 2 47.5
3 3 50
4 4 52.5
5 5 55
>
If you still have something different in mind please let me know.

Anoushiravan R
- 21,622
- 3
- 18
- 41
-
Thank you! I am slowly developing my R skills and get tripped up on little coding errors on this basic function: the output from this code isn't quite what i am after ... i'd like to be able to submit a string of say 4 different secondary scores and get their final scores as per the values of x above -- e.g. submitting c(1, 2, 3, 4 ,5) , the output would be scores of 45 47.5 50 52.5 55 – rosemarykb Mar 09 '21 at 19:08
-
Oh I'm sorry, I just changed my code, hopefully this is what you are looking for. – Anoushiravan R Mar 09 '21 at 19:41