user1554925
user1554925

Reputation: 55

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!

Upvotes: 1

Views: 97

Answers (4)

Shree
Shree

Reputation: 11140

There is no need to use loops. Here's the simplest way -

data <- data - 360*(data > 200)

Demo -

set.seed(1)
numbers <- 1:500
data <- sample(numbers)

head(data)
# [1] 133 186 286 452 101 445

data <- data - 360*(data > 200)

head(data)
# [1] 133 186 -74  92 101  85

Upvotes: 1

vaettchen
vaettchen

Reputation: 7659

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}
}

Upvotes: 1

Manos Papadakis
Manos Papadakis

Reputation: 593

Well a simple answer is this

x[x>200] = x[x>200] - 360
  1. x>200: return a logical vector were each value thas is greater than 200 is TRUE and other FALSE
  2. Use the logical vector to access the element of your initial vector. Assign or access only the element that has a TRUE value in the logical vector

Your code is wrong because you are using wrong the operator [. It must throw an error.

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

This is the correct way. You must read R from the start to understand better the operators...

Upvotes: 1

Henry Cyranka
Henry Cyranka

Reputation: 3060

I would use ifelse

numbers = 1:500
data=  sample(numbers)

new_numbers <- ifelse(numbers >200,numbers-360, numbers)
new_numbers

Upvotes: 0

Related Questions