R在同名中使用get() [英] R using get() inside colnames

查看:41
本文介绍了R在同名中使用get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个常规的项目字符串:

i have a general item string:

item='shoes'

然后我使用:

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')

我尝试做:

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

我有:

could not find function "get<-"

错误

推荐答案

我会在 assign() -ed对象中创建名称.不确定第二次分配的成功机会,因为我通常希望 sapply 返回一个矩阵而不是一个数据帧,这似乎是您的期望:

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

names 函数将与列表,数据框和向量一起使用,但是我认为它与矩阵的匹配不是特别好.它不会引发错误(正如我预期的那样),而是在看起来很不合适的矩阵上创建一个 names 属性.特别是,它不会为矩阵设置行名或列名.如果您想要将列名分配给矩阵的方法,则可能会成功:

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

这篇关于R在同名中使用get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆