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

查看:21
本文介绍了R 在 colnames 中使用 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() 修饰的对象中创建名称.不确定第二次分配的成功机会,因为我通常希望 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 在 colnames 中使用 get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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