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)
}
head
? With no second argumenthead
returns the first 6 elements. – IRTFM