【发布时间】:2013-04-15 05:04:51
【问题描述】:
使用c() 和append() 有什么区别?有吗?
> c( rep(0,5), rep(3,2) )
[1] 0 0 0 0 0 3 3
> append( rep(0,5), rep(3,2) )
[1] 0 0 0 0 0 3 3
【问题讨论】:
-
c也是具有多种 S3 方法的原语(请参阅methods("c"))
使用c() 和append() 有什么区别?有吗?
> c( rep(0,5), rep(3,2) )
[1] 0 0 0 0 0 3 3
> append( rep(0,5), rep(3,2) )
[1] 0 0 0 0 0 3 3
【问题讨论】:
c 也是具有多种 S3 方法的原语(请参阅methods("c"))
您使用它的方式在c 和append 之间没有区别。 append 的不同之处在于它允许将值插入到向量中在某个位置之后。
例子:
x <- c(10,8,20)
c(x, 6) # always adds to the end
# [1] 10 8 20 6
append(x, 6, after = 2)
# [1] 10 8 6 20
如果您在 R 终端中键入 append,您会看到它使用 c() 附加值。
# append function
function (x, values, after = length(x))
{
lengx <- length(x)
if (!after)
c(values, x)
# by default after = length(x) which just calls a c(x, values)
else if (after >= lengx)
c(x, values)
else c(x[1L:after], values, x[(after + 1L):lengx])
}
您可以看到(注释部分)默认情况下(如果您没有像示例中那样设置after=),它只会返回c(x, values)。 c 是一个更通用的函数,可以将值连接到 vectors 或 lists。
【讨论】: