Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将for循环值添加到向量中_R_Loops_For Loop_Vector - Fatal编程技术网

如何将for循环值添加到向量中

如何将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

我做了如下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`
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如果答案有帮助,请点击左侧的复选标记。每个帖子你只能接受一个答案。如果答案有帮助,请点击左边的复选标记。每个帖子只能接受一个答案。