简体   繁体   English

在R函数中使用for循环

[英]Using for loops within functions in R

Goal: take a data.frame with headers and return a new data.frame with additional variables created from calculations within a function. 目标:获取带有标题的data.frame并返回一个新的data.frame,其中包含从函数内的计算创建的其他变量。

My existing code works for creating a transform of a data.frame: 我现有的代码可用于创建data.frame的转换:

transform<- function(x) {
  transformtemp<- x
  transformtemp[1]<- x[1]
  for(i in 2:length(x)) {
    transformtemp[i]<- x[i] + 0.9*transformtemp[i-1]
  }
  transformscale<- sum(x)/sum(transformtemp)
  x<- transfomrtemp*transformscale
}

x[]<- lapply(x,transform)

With this code, I get back a data.frame with the function applied to all columns of my data. 通过此代码,我获得了一个data.frame,该函数已应用于我的数据的所有列。

I need Help with: 1. As of now, this code only uses 0.9 as my decay parameter. 我需要帮助:1.到目前为止,此代码仅将0.9用作我的衰减参数。 I want to create output using more decay parameters, say decay<- seq(0,1,0.1) and save them for use. 我想使用更多的衰减参数来创建输出,例如衰减<-seq(0,1,0.1)并保存以供使用。 2. I want the output to be the original data plus new columns of data with the function applied at the different decay rates, with names like "column1_0.9", "column1_0.8", "column2_0.9" etc. 2.我希望输出为原始数据加上数据的新列,并以不同的衰减率应用函数,其名称为“ column1_0.9”,“ column1_0.8”,“ column2_0.9”等。

I have tried using another loop with a changing decay rate but can't seem to get it right. 我尝试使用衰减率不断变化的另一个循环,但似乎无法正确处理。 I hope this all makes sense and let me know if I need to clarify further. 我希望这一切都有道理,如果需要进一步澄清,请告诉我。

All the best and thanks! 一切顺利,谢谢!

You function without assigning to the original data: 您无需分配原始数据即可运行:

mytransform<- function(x) {
  transformtemp<- x
  transformtemp[1]<- x[1]
  for(i in 2:length(x)) {
    transformtemp[i]<- x[i] + 0.9*transformtemp[i-1]
  }
  transformscale<- sum(x)/sum(transformtemp)
  x<- transformtemp*transformscale
}

A <- do.call(data.frame, lapply(mtcars,mytransform))

Let's make it more efficient with the filter function: 让我们通过filter功能提高效率:

mytransform1 <- function(x, d) {
  y <- filter(x, d, sides=1, method="recursive")

  transformscale<- sum(x)/sum(y)
  c(y*transformscale)
}

B <- do.call(data.frame, lapply(mtcars, mytransform1, d=0.9))

all.equal(A, B)
#[1] TRUE

Now we add support for multiple decay rates with an additional sapply loop: 现在,我们通过一个附加的sapply循环添加了对多种衰减率的支持:

mytransform <- function(x, d) {
  y <- sapply(d, function(d, x) c(filter(x, d, sides=1, method="recursive")), x=x)
  transformscale<- sum(x)/colSums(y)
  t(t(y)*transformscale)
}
C <- do.call(data.frame, lapply(mtcars, mytransform, d=c(0.9, 0.8)))
all.equal(B, setNames(C[,seq_along(B)*2-1], names(B)))
#[1] TRUE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM