如何将for循环值添加到向量中
我做了如下for循环,得到了10个值,但我需要将这些值转换成一个向量。我怎么做?我需要框绘这些值如何将for循环值添加到向量中,r,loops,for-loop,vector,R,Loops,For Loop,Vector,我做了如下for循环,得到了10个值,但我需要将这些值转换成一个向量。我怎么做?我需要框绘这些值 oma <- function(y){ x <- 6.1 (x^y*exp(-x))/funktio(y) } oma(10) y <- 1:10 for(i in y) print(oma(i)) oma您可以这样做 result = numeric(length = 10) ## only good if `y` is of the form `1:n` f
oma <- function(y){
x <- 6.1
(x^y*exp(-x))/funktio(y)
}
oma(10)
y <- 1:10
for(i in y)
print(oma(i))
oma您可以这样做
result = numeric(length = 10)
## only good if `y` is of the form `1:n`
for (i in y) {
result[i] = oma(i)
}
## Safer version, works even if `y` doesn't start at 1 and increment by 1
result = numeric(length = length(y))
for (i in seq_along(y)) {
result[i] = oma(y[i])
}
您在oma
中所做的一切都是矢量化的,因此如果funktio
也进行了矢量化,您可以直接转到result=oma(y)
,而无需循环。您可以这样做
result = numeric(length = 10)
## only good if `y` is of the form `1:n`
for (i in y) {
result[i] = oma(i)
}
## Safer version, works even if `y` doesn't start at 1 and increment by 1
result = numeric(length = length(y))
for (i in seq_along(y)) {
result[i] = oma(y[i])
}
您在oma
中所做的一切都是矢量化的,因此如果funktio
也进行了矢量化,您可以直接转到result=oma(y)
,无需循环。您可以使用sapply
:
vec <- sapply(y, oma)
vec您可以使用sapply
:
vec <- sapply(y, oma)
vec我们可以使用lappy
vec <- unlist(lapply(y, oma))
vec我们可以使用lappy
vec <- unlist(lapply(y, oma))
vec如果答案有帮助,请点击左侧的复选标记。每个帖子你只能接受一个答案。如果答案有帮助,请点击左边的复选标记。每个帖子只能接受一个答案。