将函数应用于 data.frame 的每一列并组织输出(Apply a function to each column of a data.frame and organize the output)

`````` x <- c(5,2,-4,-6,-2,1,4,2,-3,-6,-1,8,9,5,-6,-11)
``````

``````myfunction <- function(x){
n <- length(x)
fx <- numeric(n)
fx[1] <- min(x[1],0)
for(i in 2:n){fx[i] <- min(0,fx[i-1]+x[i])}
fx

x_min <-min(x)
fx_min <- min(fx)

fx_05 <- numeric(n)
fx_05[1] <- min(fx[1],0)
for (i in 2:n) {
if (sum(fx_05[i-1]+x[i])>0) {
fx_05[i] <- 0
} else if ((sum(fx_05[i-1]+x[i]))<(fx_min*0.5)) {
fx_05[i] <- (fx_min*0.5)
} else { fx_05[i] <- sum(fx_05[i-1]+x[i]) }
}
fx_05
as.data.frame(matrix(c(x, fx_05), ncol = 2 ))
}
xx <- myfunction(x)
``````

``````    V1   V2
1    5  0.0
2    2  0.0
3   -4 -4.0
4   -6 -8.5
5   -2 -8.s
6    1 -7.5
7    4 -3.5
8    2 -1.5
9   -3 -4.5
10  -6 -8.5
11  -1 -8.5
12   8 -0.5
13   9  0.0
14   5  0.0
15  -6 -6.0
16 -11 -8.5`
``````

``````df <- data.frame(x <- c(5,2,-4,-6,-2,1,4,2,-3,-6,-1,8,9,5,-6,-11),
y <- c(5,2,-4,-6,-2,1,4,2,-3,-6,-1,8,9,5,-6,-11),
z <- c(5,2,-4,-6,-2,1,4,2,-3,-6,-1,8,9,5,-6,-11))
``````

``````output <- myfunction(df)
``````

``````outputs <- data.frame(sapply(df, myfunction))
``````

data.frame 输出的形式不正确。 data.frame 的每个原始列应该是 2 列。

``````x <- lapply(df, myfunction)
``````

``````x <- sapply(df, myfunction)
``````

``````df2 <- do.call(cbind, x)
``````

``````names(df2) <- NULL
df2
# 1    5  0.0   5  0.0   5  0.0
# 2    2  0.0   2  0.0   2  0.0
# 3   -4 -4.0  -4 -4.0  -4 -4.0
# 4   -6 -8.5  -6 -8.5  -6 -8.5
# ....
``````

边注：

``````x <- apply(df, MARGIN = 2, myfunction)
``````