[SOLVED] r: nesting a for loop within a custom function

Issue

I have an anonymous function that I use to apply a double-exponential transformation to, and it works well for me with hard-coded values:

custom_func <- function(x) {
  0.01^(0.95^(x/max(x)*100))
}

df$newVar <- custom_func(df$var)

df$newVar

It returns the expected transformed variable:
It returns the expected transformed variable

However, I want to use create a version that will ingest multiple parameters for the second exponent and add them as permanent vectors to my data frame. My attempt doesn’t add anything to the dataframe and having trouble understanding how to fix this:

alpha <- seq(0.85, 0.95, by= .01)

dblExponential <- function(a,x){
  for (i in alpha) {
    0.01^(a^(x/max(x)*100))
  }
}

dblExponential(alpha, df$var)

df

Solution

Functions in R do not need an explicit return statement if you only want to use the value of the last evaluated statement. That works nicely in your simple function (your first code block).

In the second case, if I understand correctly, you want to return multiple time series that are computed one after the other in a loop. That is, you will have to compose the result data frame explicitly in the function and then return this result data frame.

An example based on your second code block

# Function definition (Note that the common convention is to define functions at the
#        top of any script so that people can understand the structure more easily.)
#
dblExponential<- function(a, x){
  # Prepare result data frame
  result_df <- data.frame(x)
  # loop through the sequence
  for (i in a) {
    # Compute column for value i
    result_column <- 0.01^(i^(x/max(x)*100))
    # Define name of column in the resulting data frame
    result_column_name <- as.character(i)
    # Add the column to the data frame
    result_df[result_column_name] <- result_column
  }
  # Return the result data frame
  return(result_df)
}

# Create example data frame
df <- data.frame(c(1, 2, 3, 4, 5, 6, 7))
colnames(df) <- c("var")

# Your sequence of exponents
alpha <- seq(0.85, 0.95, by= .01)

# Call to the function, assign the return value to df2
df2 <- dblExponential(alpha,df$var)

# print df2
df2

Answered By – 0range

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.