How to change the elements of specific position?

Are you trying to multiply the odd rows because you actually want to multiply all the BloodSugar values where there is a particular corresponding value of Gender (in this case, “F”)? If so, you can do that directly, in a way that would work no matter how the rows are ordered.

For instance, if you wanted to reduce BloodSugar by 20% for all observations where Age is greater than 40, you might do:

PatientProfile$BloodSugar[PatientProfile$Age > 40] <- PatientProfile$BloodSugar[PatientProfile$Age > 40] * 0.8

This uses an extraction operator to extract only the elements of BloodSugar where the corresponding element of Age passes a test, and then replaces those extracted elements with new values. The elements that did not pass the test are left untouched.

So you could do something similar, testing for a particular value of Gender instead of Age.

P.S. Since this is a general question about R, rather than anything specific to the RStudio IDE, you might consider changing the category — it keeps things tidy :sparkles: and helps make sure your question attracts helpers with relevant interests!

4 Likes