-1

I just learned a new way to use 'length<-' in an apply function something like:

l<- list(c(1,1,2,2,2),c(1,2),c(1,2,2,2),c(1,2,2))
sapply(l, `length<-`, 6)

creates a 4x6 matrix,

     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    2    2    2
[3,]    2   NA    2    2
[4,]    2   NA    2   NA
[5,]    2   NA   NA   NA
[6,]   NA   NA   NA   NA

that is cool by itself. However I realized that

`length<-`(l[[1]],6)

will not change l[[1]], so that

lapply(l, `length<-`, 6)

will not change l.

I would like to know if that is always the case for every single function that accepts a value assigned to it, such as 'dim<-', 'attr<-', etc. If so, is that a behaviour codified in the R parser?

Carlos Alberto
  • 598
  • 3
  • 9

1 Answers1

1

length(x) <- 6 does not just do "length<-"(x, 6) but x <- "length<-"(x, 6). This is how lhs functions work in R. See the first answer in `levels<-`( What sorcery is this?

In your first example sapply creates a new matrix which you display us. In the second example "length<-" creates a new vector of length 6 but that will not be assigned to any name.

Community
  • 1
  • 1
Ott Toomet
  • 1,894
  • 15
  • 25