【问题标题】:r: nesting a for loop within a custom functionr:在自定义函数中嵌套一个 for 循环
【发布时间】:2018-11-23 13:04:44
【问题描述】:

我有一个匿名函数,我用它来应用双指数变换,它适用于我的硬编码值:

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

df$newVar <- custom_func(df$var)

df$newVar

它返回预期的转换变量:

但是,我想使用创建一个版本,该版本将为第二个指数摄取多个参数,并将它们作为永久向量添加到我的数据框中。我的尝试没有向数据框添加任何内容,并且无法理解如何解决此问题:

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

【问题讨论】:

    标签: r function for-loop


    【解决方案1】:

    如果你只想使用最后一个评估语句的值,R 中的函数不需要显式的 return 语句。这在您的简单函数(您的第一个代码块)中效果很好。

    在第二种情况下,如果我理解正确,您希望返回多个时间序列,这些时间序列在循环中一个接一个地计算。也就是说,您必须在函数中显式组合结果数据框,然后返回此结果数据框。

    基于您的第二个代码块的示例

    # 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
    

    【讨论】:

    • 太好了,谢谢。两个后续行动: 1. 现在我需要做的就是将其添加到一个新的数据框中,其余数据是在这个和旧数据框上运行cbind? 2. 本网站上的信息或文档均未解释“操作顺序”或如何构建如此复杂的功能。关于读什么有什么建议吗?再次感谢!
    • @enriqueStateSpacias 上面的函数为您提供了一个包含原始向量的新数据框。如果您只想将新列包含到原始数据框 df 中,您可以 1)使用 cbind 组合 dfdf2,2)直接在函数中修改 df(它是一个全局变量) 但那将是不好的风格,3) 将整个数据框交给函数,而不仅仅是列,或者 4) 将函数调用放在循环中,而不是在函数中包含循环。我不确定我是否理解你的第二个问题。您可能想了解一般的函数式编程。
    猜你喜欢
    • 2020-01-23
    • 2023-03-02
    • 2021-09-15
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多