0

I read the following codes in a book. Not quite sure of the 'names<-' part in last line.

Could someone provide some reference for this? Is this related to the functions forms mentioned in section 6.8 of https://adv-r.hadley.nz/functions.html ? Or they define the attributes in some way? Thanks.

bs.quantile <- function(v, p=c(0, 0.25, 0.5, 0.75, 1))
{
  b <- 1-p
  k <- floor((ps <- p*length(v))+b)
  beta <- ps+b-k
  'names<-'((1-beta)*(v <- sort(v))[k]+beta*(ifelse(k<length(v), v[k+1], v[k])), p)
}

There are several other places where the author use this approach.

‘class<-‘(tree, "dectree.frac")
‘class<-‘(list(prior=cc/sum(cc),cond=sapply(avc, 
function(avc1) t(apply(avc1, 1, "/", colSums(avc1))))),"nbc")
}
Ken
  • 17
  • 4
  • Good find, @Henrik. Questions on functions/issues that include specials like `<-` can be especially hard to find since most search engines seem to optimize them out. – r2evans Sep 14 '20 at 18:26
  • Ken, the answers in Henrik's link give a little more info than I did here in my answer. I'm going to mark this question as a dupe (not a bad thing), but it would be nice if you accepted this anyway. Thanks! – r2evans Sep 14 '20 at 18:28
  • 1
    Regarding @r2evans's point 1, ‘class<-‘ was due to pure laziness. I just copied the code from the book directly. – Ken Sep 14 '20 at 23:22

1 Answers1

1
  1. ‘class<-‘ (with single quotes, whether fancy or straight-ascii ') is wrong, likely a side-effect of copying and pasting and/or misinterpreting somebody else's code. (MS Word does this a lot ... never never never write/edit R code in Word, R is intolerant of these fancy-niceties :-).

    Typically, it should be backticks instead, as in `class<-` and `names<-`.

  2. Typically, one would see something like

    vec <- c(1, 3, 11)
    names(vec) <- c("a", "BB", "quux")
    vec
    #    a   BB quux 
    #    1    3   11 
    

    That last call is actually calling a special form of a function call `names<-` (not names itself), which tells R that it should do something different when names(...) is called on the left-hand side (LHS) of an assignment operator (= or <- in R).

    Sometimes, coders try to be slick (code-golf) by calling the function directly so that they can get the returned value without necessarily changing the original variable's value. For instance:

    vec <- c(1, 3, 11)
    `names<-`(vec, c("a", "BB", "quux"))
    #    a   BB quux 
    #    1    3   11 
    vec
    # [1]  1  3 11
    

    With `class<-`, it is changing the class of an object "inline".

r2evans
  • 141,215
  • 6
  • 77
  • 149