rfunctionindexingtext2vec

R function with reference to argument without evaluating it


islands1<-islands #a named num (vector)

data.frame(island_col=names(islands1), number_col=islands1,row.names=NULL)

This creates a dataframe consisting of two columns, the first contains the names from the named vector and is called "island_col", the second column contains the numbers and is named "number_col". No problems here.

Now suppose I write a function because I have a bunch of these named vectors I'm converting into dataframes. Each vector is numbered such as islands1, islands2, etc.

dfunc<-function(x) data.frame(island_col=names(x), as.name(x)<-(x),row.names=NULL) Here is a function that uses data.frame to convert the named vector into a dataframe

firstdf<-dfunc(islands) I use the function on the "islands1" named vector. I want number column to be named "islands1" because that's the name of the argument but R doesn't understand this and instead attemps to evaluate the argument itself. I've tried variations using the paste0 function and as.character but can't get it to work.

Also, yes, I understand that all this leading up to these named vectors should probably have been done with lapply so I would have a list to work with at this point. I spent many hours going that route (see my other question) but ultimately could not get it to work and have deadlines to consider. More generally, I am trying to get a better understanding of how and when R evaluates arguments and how to index objects.


Solution

  • I want number column to be named "islands1" because that's the name of the argument ...

    Use deparse and substitute as follows

    islands1 <- c(a = 1, b = 2, c = 3)
    islands2 <- c(d = 3, e = 2, g = 1)
    
    func <- function(x){
      out <- data.frame(island_col = names(x), xSym = x)
      names(out)[2] <- deparse(substitute(x))
      out
    }
    
    func(islands1)
    #R   island_col islands1
    #R a          a        1
    #R b          b        2
    #R c          c        3
    func(islands2)
    #R   island_col islands2
    #R d          d        3
    #R e          e        2
    #R g          g        1