0
votes

I'm creating a function that takes two inputs: delta, and length. The function modifies an existing vector - let's call this vector base - by delta for 'length' specified elements.

I need to create a new vector, let's call it 'adjusted'. This vector, adjusted, needs to populate based on one condition: If the index value for the base vector is less than the length parameter specified in the function input, then I want to increase the base vector by delta for all elements less than length. All elements in the base vector greater than the specified length parameter are to remain the same as in base vector.

Here is an example of my code: I have tried to implement the logic in two ways. 1. Using an ifelse because it allows for vectorized output. 2. Using an if else logic.

    adjusted <- vector() #initialize the vector.

#Create a function. 
Adjustment <- function(delta, length) {

  ifelse((index < length), (adjusted <- base + delta), (adjusted <- base)) 

  head(adjusted)
}

    #Method 2. 
   Adjustment <- function(delta, length) {

      if (index < length) {
            adjusted <- base + delta
        }
      else {adjusted <- base}

      head(adjusted)
    }

Where I am experiencing trouble is with my newly created vector, adjusted, will not populate. I'm not quite sure what is happening - I am very new to R and any insight would be much appreciated.

EDIT: With some advice given, I was able to return output. The only issue is that the 'adjusted' vector is now 2x the length of the index vector. I see that this is happening because there are two calculations, one in the if value is true, and one in the if value is false. However, I want the function to write to the vector adjusted only in the elements for which the index is less than the parameter length.

For example. Let's say that the index vector is 10. If I set length to 3, I want adjusted to reflect a change for elements 1:3 and the same information in base for 4:10.

My code reflects adjusted is now length 20. How can I approach this and maintain the original value of the vector?

adjusted <- c()

Adjustment <- function(delta, length) {
ifelse(index < length, adjusted <<- c(adjusted, base + delta), adjusted <<- c(adjusted, base))

  head(adjusted)
}
2
Why exactly are you using head? With no second argument head returns the first 6 elements.IRTFM
Just for self check. I wanted to return the first 5 observations of adjusted to see if the calculation was functioning properly.datanalyst

2 Answers

2
votes

How about using a bit of Boolean algebra:

  adjusted <- base + delta*(base > length)
0
votes
Adjustment <- function(delta, length) {

if (index < length) {
for(i in 1:length-1){
  adjusted[i] <- base[i] + delta
}
}
else {adjusted <- base}

head(adjusted)

}


index=2
length=5
base <- c(1,2,3,4,5,6,7,8,9,10)
delta = 2

Adjustment(delta,length)

This returns a vector that has all values < indexVALUE from base vector added by delta.