【问题标题】:Difference between c() and append()c() 和 append() 的区别
【发布时间】: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"))

标签: r function


【解决方案1】:

您使用它的方式在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。

【讨论】:

    猜你喜欢
    • 2016-12-08
    • 2014-12-07
    • 2013-10-21
    • 2021-06-10
    • 2021-09-30
    • 2018-08-05
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多