Tuesday, October 6, 2015

R 里面 apply, tapply 在这种情况下,怎么用?

http://www.mitbbs.com/article_t/Statistics/31391509.html

发信人: xianzai (现在), 信区: Statistics
标  题: R 里面 apply, tapply 在这种情况下,怎么用?
发信站: BBS 未名空间站 (Tue Oct  6 14:30:37 2015, 美东)

代码如图所示,怎样把最后的for 循环,改为用类似于 apply的函数?

# suppose u and v returned by fun1()
# fun1() is a R-script with about 200 lines
u <- 3.8
v <- 53.41

# suppose x and y returned by fun2()
# fun2() is a R-script with about 500 lines
x <- 3.8
y <- 53.41

# demo fun3(), actual function is much more complicated
fun3 <- function(x1, x2, x3, x4, x5, x6, x7) {
    w <- x1^2 + sqrt(x2+x3) - 0.75*x4 + exp(x5)
    z <- sin(x2)/x7 + x6/(x3+x4) return(w+z)
}

# create a random table
dailyrecord <- data.frame(a = rnorm(500), b = rnorm(500), c = rnorm(500),
    d = rnorm(500), e = rnorm(500), f = rnorm(500), g = rnorm(500))

result <- rep(0, 500)

# for - loop
for (k in 1 : 500) {
    result[k] <- fun3(u, v, x, y, dailyrecord$a[k], dailyrecord$e[k],
dailyrecord$f[k]) }




谢谢

No comments:

Post a Comment