Search code examples
rif-statementvectorsubtraction

mathematically manipulate specific elements of vector/object in R


I'm wondering how I can subtract a specific value from elements in a vector that are greater than a threshold I set?

for example, if my data is defined as:

numbers = 1:500
data=  sample(numbers)

I now have a random list of numbers between 1 and 500.

I now want to subtract 360 from each value in this vector that is greater than 200. Logically i want to write a for loop with an if statement to do this. I have gone as far to write code that looks like this:

for (i in 1:length(data)) {
       if data[i]>200 {
       data[] - 360
     } else {
       data[] - 0
     }
}

This clearly does not work but I am stumped as to what I can do to achieve my goal. Since I will need to plot these data afterwards, I need them to stay in their original order within the output vector. Thanks a ton for the help!


Solution

  • ifelse() is perfect for the purpose, you can use the data vector of your sample:

    data <- ifelse( data > 200, data - 360, data )
    

    So merely to give another taste:

    set.seed( 1110 )                                      # make it reproducible
    data <- sample( numbers )
    head( data, 10 )
    [1] 242 395 440 287 110  46 241 489 276 178
    data[ data > 200 ] <- data[ data > 200 ] - 360        # replace inline
    head( data )
    [1] -118   35   80  -73  110   46 -119  129  -84  178
    

    Your loop would have worked as well after correcting some mistakes, see below:

    for (i in 1:length(data)) {
            if( data[i]>200 ){
            data[ i ] <- data[ i ] - 360}
    }