按行迭代,不带FOR-非泛型函数FOR;套用; #自定义DF 演示
对于这类问题,没有一刀切的解决方案。在这种特殊情况下,不需要循环或应用。您可以只使用向量化操作按行迭代,不带FOR-非泛型函数FOR;套用; #自定义DF 演示,r,R,对于这类问题,没有一刀切的解决方案。在这种特殊情况下,不需要循环或应用。您可以只使用向量化操作 cycle <- function(k) { k } lapply(1:nrow(demo), cycle) # use sequence instead of DF itself 还可以将附加参数传递给lappy中的函数。比如你能做什么 library(dplyr) demo %>% mutate(res2=x1*2 + lag(x1)*3) # this values the fir
cycle <- function(k) { k }
lapply(1:nrow(demo), cycle) # use sequence instead of DF itself
还可以将附加参数传递给lappy
中的函数。比如你能做什么
library(dplyr)
demo %>% mutate(res2=x1*2 + lag(x1)*3)
# this values the first value as NA rather than 0
循环
demo$res <- c(0,tail(demo$x1,-1)*2 + head(demo$x1,-1)*3)
library(dplyr)
demo %>% mutate(res2=x1*2 + lag(x1)*3)
# this values the first value as NA rather than 0
cycle <- function(k, d) { paste(k, d[[1]][k]) }
lapply(1:nrow(demo), cycle, demo)