我想在函数上创建一个for循环,它遍历向量的项目。我想生成一个由结果组成的向量:
funk <- function(x){return (x+1)}
ul <- seq(0,1,0.001)
test1 <- NULL
for (i in ul){
test1 <- data.frame(column = rbind(test1, funk(ul[i])))
}
我得到了结果
test1
column
1 1
我想得到
column
1 1
2 1.001
3 1.002
...
我在循环中做错了什么?
答案 0 :(得分:1)
for循环,尝试:
sapply(ul, funk)
如果你真的想使用for循环,这就是解决方案
funk <- function(x){return (x+1)}
ul <- seq(0,1,0.001)
## always create the vector first so R allocates memory
test1 <- rep(NA, length(ul))
for (i in 1:length(ul))
{
test1[i] <- funk(ul[i])
}
答案 1 :(得分:0)
在循环中它将是:
funk <- function(x){return (x+1)}
ul <- seq(0,1,0.001)
test1 = list()
for (i in 1:length(ul)){
test1[[i]] = data.frame(column= funk(ul[i]))
}
test1 = do.call("rbind", test1)