简体   繁体   中英

What's the equivalent of `cons` in R?

In lisp you can append to a list (not an atomic vector) with the cons form. What's the equivalent function in R ? I tried Googling, but only got entries seeking pros and cons of R.

Example:

x <- list("A")
y <- c(x, "B")
y
[[1]]
[1] "A"

[[2]]
[1] "B"

In R the c function is overloaded. 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. I suppose the car would be list_name[[1]] and the cdr would be 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.

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 <- 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). 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. You could even name the elements in your vector 'car' and 'cdr', as in

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). In short, there are no 'cons' (as in lisp) in R.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM