demo <- data.frame(step = seq(1:5), x1 = sample(1:5, 5), x2 = sample(5:9, 5), xx = 0)
我有DF并希望在“apply”中更改其中一个列,但我不想使用全局变量,因此,我试图在FUN中传递环境并在此环境中分配变量。 / p>
# This method works but it looks like hardcode because I have to use global name "demo"
cycle <- function(k, d, e) { demo[k, 4] <<- k }
lapply(1:nrow(demo), cycle, demo, environment())
这些方法不起作用:
# In this case R shows error - "k" is not defined, although, it should work as a closure
cycle <- function(k, d, e) { with(e, d[k, 4] <- k) }
lapply(1:nrow(demo), cycle, demo, environment())
# I tried "assign" new value to DF but this did not change it, "xx" column is still 0
cycle <- function(k, d, e) { assign("d[k, 4]", k, envir = e) }
lapply(1:nrow(demo), cycle, demo, environment())
# This also does not change values in last column
cycle <- function(k, d, e) { assign(gsub("#", k, d), k, envir = e) }
lapply(1:nrow(demo), cycle, "demo[#,4]", environment())
问题:如何在不使用此DF的全局名称的情况下从FUN更改DF中的特定列?
只是一个建议,也许我错误地定义了环境?
更新:我需要使用“lapply”,因为我需要将几个动作放入一个函数中,并为每一行迭代执行它,例如我可能想以类似的方式在浮动窗口上应用PCA:
DF = data.frame(...)
x1 x2 x3 res
1 2 3 0
4 5 6 0
7 8 9 0
for (k in 1:3)
{
x = DF[k:k + 2,]
pc <- princomp(x, ...)
ls <- loadings(pc) # or ls <- lm(x + 0)
values <- c(DF[k,1] * ls[1] + DF[k,2] * ls[2])
}
DF$res <- values
我需要在“apply”中执行此循环作为回调,如果我想使用“apply”而不是“for”循环,如何获取此执行的结果(值)?
作为一个例子,我希望在本文http://www.r-bloggers.com/structural-arbitrage-trading-the-equity-curve/中使用类似“applyWeeklySMA”的功能,但我想用“lapply”替换循环,这可能吗?
答案 0 :(得分:1)
DF <- as.data.frame(matrix(1:15, ncol = 3))
pcl <- function(k, data) {
x <- data[k:(k + 2), ]
pc <- princomp(x)
load <- loadings(pc)
as.matrix(data[k, 1:2]) %*% load[1:2]
}
DF$res <- c(lapply(1:3, pcl, DF), rep(0, 2))
这就是我想你正在努力实现的目标。请注意,函数pcl在调用环境中根本没有依赖关系。