R using get() inside colnames

与世无争的帅哥 提交于 2021-02-04 08:01:05

问题


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


回答1:


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 }
                         }
}


来源:https://stackoverflow.com/questions/20481785/r-using-get-inside-colnames

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!