# Custom DF
demo <- data.frame(step = seq(1:5), x1 = sample(1:5, 5), x2 = sample(5:9, 5))
# Add column with a result of some operation on subset before this row
demo <- transform(demo, res = 0)
# Fill in "res" with result of operation on several rows (subset) and some coefficients
for (k in 2:nrow(demo)) demo$res[k] <- demo$x1[k] * 2.0 + demo$x1[k - 1] * 3.0
问题:是否可以用&#34; apply&#34;替换循环。或具有这些条件的任何其他迭代器
我可以这样模拟索引:
cycle <- function(k) { k }
lapply(1:nrow(demo), cycle) # use sequence instead of DF itself
此代码将打印从1到5的索引,但如何将demo作为参数传递到&#34; cycle&#34;?
答案 0 :(得分:2)
对于这类问题,没有一个通用的解决方案。在这种特殊情况下,您不需要循环或应用。您可以使用向量操作
$('#fixModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget),
hclub = button.data('hclubid'),
modal = $(this),
imgpath = "/images/clubcrests/",
homecrest = imgpath + hclub + '.jpg',
gencrest = imgpath + 'generic.jpg',
homecrestsrc;
$.get(homecrest).done(function () {
homecrestsrc = "<img src='" + homecrest + "'>"
}).fail(function () {
homecrestsrc = "<img src='" + gencrest + "'>"
}).always(function () {
modal.find('.fixmodhomec').html(homecrestsrc);
});
})
demo$res <- c(0,tail(demo$x1,-1)*2 + head(demo$x1,-1)*3)
库具有很好的dplyr
函数,可以使这些操作更容易。
lead/lag
还可以将其他参数传递给library(dplyr)
demo %>% mutate(res2=x1*2 + lag(x1)*3)
# this values the first value as NA rather than 0
中的函数。例如,您可以
lapply
正在迭代的参数作为第一个参数传递,然后您可以在cycle <- function(k, d) { paste(k, d[[1]][k]) }
lapply(1:nrow(demo), cycle, demo)
调用本身中包含其他参数,并将它们传递给子函数。