28

我刚刚开始学习 R 并且遇到了一个让我相当困惑的问题。我的目标是创建一个空向量并向其附加元素。似乎很容易,但我在 stackoverflow 上看到的解决方案似乎不起作用。

以机智,

>     a <- numeric()
>     append(a,1)
[1] 1
>     a
numeric(0)

我无法弄清楚我做错了什么。有人想帮助新手吗?

4

2 回答 2

41

append does something that is somewhat different from what you are thinking. See ?append.

In particular, note that append does not modify its argument. It returns the result.

You want the function c:

> a <- numeric()
> a <- c(a, 1)
> a
[1] 1
于 2013-01-18T03:55:11.793 回答
5

您的a向量不是通过引用传递的,因此当它被修改时,您必须将其存储回a. 您无法访问a并期望它被更新。

您只需将返回值分配给您的向量,就像 Matt 所做的那样:

> a <- numeric()
> a <- append(a, 1)
> a
[1] 1

尽管您的使用很好,但马特是对的,这c()是更可取的(更少的击键和更多功能) 。append()

于 2013-01-18T04:12:40.647 回答