[英]What's the equivalent of `cons` in R?
In lisp you can append to a list (not an atomic vector) with the cons
form. 在Lisp中,您可以使用
cons
形式追加到列表(而不是原子向量)。 What's the equivalent function in R
? R
的等效函数是什么? I tried Googling, but only got entries seeking pros and cons of R. 我尝试了Googling,但只获得了寻求R优缺点的条目。
Example: 例:
x <- list("A")
y <- c(x, "B")
y
[[1]]
[1] "A"
[[2]]
[1] "B"
In R the c
function is overloaded. 在R中,
c
函数已重载。 It concatenates lists, atomic vectors, and many other structures. 它连接列表,原子向量和许多其他结构。
> methods(c)
[1] c.bibentry* c.Date c.noquote c.numeric_version c.person*
[6] c.POSIXct c.POSIXlt c.warnings
R lists (called "recursive" in R parlance) can be accessed using integer indices or if there are names for a particular leaf with a character value. 可以使用整数索引或存在带有字符值的特定叶子的名称来访问R列表(在R术语中称为“递归”)。 I suppose the
car
would be list_name[[1]]
and the cdr
would be list_name[-1]
. 我想这
car
是list_name[[1]]
而cdr
是list_name[-1]
。 Notice that I used different extraction functions. 注意,我使用了不同的提取函数。 As I understand LisP, the
cdr
is a list but the car
is the value in the first position, which may or may not be a list. 据我了解LisP,
cdr
是一个列表,但是car
是第一个位置的值,它可能是也可能不是列表。
It is possible to use [[
or [
in a more functional format: 可以以更实用的格式使用
[[
或[
> '[['(y, 1)
[1] "A"
> '['(y, -1)
[[1]]
[1] "B"
And you could even define a car or cdr function: 您甚至可以定义car或cdr函数:
> car <- function(z) z[[1]]
> car(y)
[1] "A"
> cdr <- function(z) z[-1]
> cdr(y)
[[1]]
[1] "B"
R language objects are all vectors which can have any length, so there's no equivelent to the cons object (ie a doublet with a left and right side). R语言对象都是可以具有任何长度的向量,因此cons对象没有等价物(即带有左侧和右侧的doublet)。 You could create a class in R that model a cons object, or you could just use vectors of lengt two and the the first element is the left and the second element is the right.
您可以在R中创建一个对cons对象建模的类,也可以只使用长度为lengt的向量,第一个元素是左侧,第二个元素是右侧。 You could even name the elements in your vector 'car' and 'cdr', as in
您甚至可以将向量中的元素命名为“ car”和“ cdr”,例如
x <- c(1,2)
names(x) <- c('car','cdr')
Also, R doesn't use pointers, or reference semantics (except for environments and things based on environments). 同样,R不使用指针或引用语义(环境和基于环境的事物除外)。 In short, there are no 'cons' (as in lisp) in R.
简而言之,R中没有“ cons”(如Lisp)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.