2

i have a general item string:

item='shoes'

then i use:

assign(paste0(item,'_list'),lapply(etc))

assign(paste0(item,'_df'),sapply(etc)) 

then i want to change the colnames of the data-frame with the names inside a character vector:

v=c('a','b','c')

i try to do:

colnames(get(paste0(item,'_df'))=v

bu i have the:

could not find function "get<-"

error

user3083330
  • 85
  • 1
  • 1
  • 7
  • 1
    I think something like `eval(parse(paste0("colnames(",item,"_df) <- v"))`, but as usual if you find yourself using `eval(parse(...))` you should probably reconsider your strategy, i.e. keep your individual items within a named list ... – Ben Bolker Dec 09 '13 at 22:09
  • thanks i never used the eval(parse()) functions – user3083330 Dec 09 '13 at 22:29

1 Answers1

2

I would create the names in the object being assign()-ed. Not sure about chances of success with the second assignment, since I generally expect sapply to return a matrix rather than a dataframe, which seems to be your expectation:

assign(paste0(item,'_list'), setNames(lapply(etc), v))

assign(paste0(item,'_df'), setNames(sapply(etc), v))

The names function will work with lists, dataframes and vectors, but I think it's not particularly well matched with matrices. It doesn't throw an error (as I expected it would) but rather creates a names attribute on a matrix that looks very out of place. In particular it does not set either rownames or colnames for a matrix. If you wanted something that did assign column names to a matrix this might succeed:

setColNames <- function (object = nm, nm) 
{ if ( class(object) %in% c("list", "data.frame", "numeric", "character") ){
    names(object) <- nm
    return(object) 
   } else{
  if ( class(object) %in% c("matrix") ){
    colnames(object) <- nm
    return(object)
  } else { object }
                         }
}
IRTFM
  • 258,963
  • 21
  • 364
  • 487