更新时间:2023-02-23 21:40:25
我会在 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 }
}
}