r:在自定义函数中嵌套for循环
我有一个匿名函数,我用它来应用双指数变换,它对硬编码值非常有效:r:在自定义函数中嵌套for循环,r,function,for-loop,R,Function,For Loop,我有一个匿名函数,我用它来应用双指数变换,它对硬编码值非常有效: custom_func <- function(x) { 0.01^(0.95^(x/max(x)*100)) } df$newVar<- custom_func(df$var) df$newVar 如果只想使用上一个求值语句的值,R中的自定义函数不需要显式的return语句。这在您的简单函数(您的第一个代码块)中非常有效 在第二种情况下,如果我理解正确,您希望返回在循环中一个接一个计算的多个时间序列。也就是
custom_func <- function(x) {
0.01^(0.95^(x/max(x)*100))
}
df$newVar<- custom_func(df$var)
df$newVar
如果只想使用上一个求值语句的值,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
#函数定义(注意,常见的惯例是在
#任何脚本的顶部,以便人们更容易理解结构。)
#
dblExponentialExcellent,成功了,谢谢。两次跟进:1。现在我需要做的就是将它添加到一个新的数据帧中,剩下的数据在这个数据帧和旧的数据帧上运行cbind
?2.本网站或文档中的任何信息都无法解释“操作顺序”或如何构建如此复杂的功能。对阅读内容有什么建议吗?再次感谢@EnriqueStateSpacia因为上面的函数提供了一个包含原始向量的新数据帧。如果您只想将新列包含到原始数据帧df
,您可以1)使用cbind
组合df
和df2
,2)直接在函数中修改df
(它是一个全局变量),但这将是一种糟糕的风格,3)将整个数据帧交给函数,而不仅仅是列,或4)将函数调用放入循环中,而不是将循环包含在函数中。我不确定我是否理解你的第二个问题。您可能想阅读有关函数式编程的一般知识。
# 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