# How to change the elements of specific position?

I created the following table using the following script.

PatientProfile<-data.frame(Age=numeric(0),Gender=character(0),BloodSugar=numeric(0))
PatientProfile<-edit(PatientProfile)
PatientProfile

Now, I am trying to multiply all my BloodSugar that comes in odd positions by 5 and leaving the rest unchanged. Here I am getting stuck! I don't know how to specify odd/even locations. Can someone help me please?

You're almost there, try to look at this

seq(1,10) %% 2
1 Like

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 and helps make sure your question attracts helpers with relevant interests!

4 Likes

You can use the recycle rule to select even/odd rows.
All you have to do is subsetting using logical vectors.

df <- data.frame(x = seq_along(10), y = sample(10))
# select even
df[c(FALSE, TRUE),]
#>    x y
#> 2  1 1
#> 4  1 3
#> 6  1 2
#> 8  1 4
#> 10 1 7
# select odd
df[c(TRUE, FALSE),]
#>   x  y
#> 1 1 10
#> 3 1  5
#> 5 1  9
#> 7 1  8
#> 9 1  6
1 Like