将值添加到R中的for循环中的向量 [英] adding values to the vector inside for loop in R
问题描述
squared <-function(x){
m <-c()
for(i in 1:x){
y< -i * i
c(m,y)
}
return(m)
}
平方(5)
为什么这会返回NULL。我希望将 i * i
值附加到 m
的末尾,并返回一个向量。有人可以指出这个代码有什么问题。
因为您没有使用任务,因此在循环中< - c()。你得到以下 -
m < - c()
m
#NULL
您可以通过分配 m $ c $来更改函数以返回所需的值
$ b $ pre $ code> squared < - function(x){
m < - c()
$($ in $ 1
$ m
$
$ b平方(5)
#[1] 1 4 9 16 25
但是这是低效的,因为我们知道结果向量的长度是5(或 x
)。所以我们希望在循环之前先分配内存。 ()循环中使用是更好的方法。
m [i]< -i(平方)< - 函数(x){
m< *
}
m
}
平方(5)
#[1] 1 4 9 16 25
$ c $另外请注意,我已经从第二个函数中删除了return()
。这不是必要的,所以它可以被删除。在这种情况下离开它是个人喜好的问题。有时候这将是必要的,就像在if()
语句中一样。 我知道问题是关于循环,但我也必须提到,使用原始的^
可以用七个字符更有效率地完成,就像这样(1:5)^ 2
#[1] 1 4 9 16 25
^
是一个原始函数,这意味着代码完全用C编写,并且是这三种方法中最有效的。 >
`^`
#函数(e1,e2).Primitive(^)
I have just started learning R and I wrote this code to learn on functions and loops.
squared<-function(x){ m<-c() for(i in 1:x){ y<-i*i c(m,y) } return (m) } squared(5) NULL
Why does this return NULL. I want
i*i
values to append to the end ofm
and return a vector. Can someone please point out whats wrong with this code.解决方案You haven't put anything inside
m <- c()
in your loop since you did not use an assignment. You are getting the following -m <- c() m # NULL
You can change the function to return the desired values by assigning
m
in the loop.squared <- function(x) { m <- c() for(i in 1:x) { y <- i * i m <- c(m, y) } return(m) } squared(5) # [1] 1 4 9 16 25
But this is inefficient because we know the length of the resulting vector will be 5 (or
x
). So we want to allocate the memory first before looping. This will be the better way to use thefor()
loop.squared <- function(x) { m <- vector("integer", x) for(i in seq_len(x)) { m[i] <- i * i } m } squared(5) # [1] 1 4 9 16 25
Also notice that I have removed
return()
from the second function. It is not necessary there, so it can be removed. It's a matter of personal preference to leave it in this situation. Sometimes it will be necessary, like inif()
statements for example.I know the question is about looping, but I also must mention that this can be done more efficiently with seven characters using the primitive
^
, like this(1:5)^2 # [1] 1 4 9 16 25
^
is a primitive function, which means the code is written entirely in C and will be the most efficient of these three methods`^` # function (e1, e2) .Primitive("^")
这篇关于将值添加到R中的for循环中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!